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
);
790 NSModule
NSModuleForSymbol(NSSymbol symbol
)
792 if ( dyld::gLogAPIs
)
793 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
794 NSModule result
= NULL
;
795 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
797 result
= ImageLoaderToNSModule(image
);
804 bool _dyld_all_twolevel_modules_prebound(void)
806 if ( dyld::gLogAPIs
)
807 dyld::log("%s()\n", __func__
);
811 bool _dyld_bind_fully_image_containing_address(const void* address
)
813 if ( dyld::gLogAPIs
)
814 dyld::log("%s(%p)\n", __func__
, address
);
815 address
= stripPointer(address
);
816 dyld::clearErrorMessage();
817 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
818 if ( image
!= NULL
) {
820 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
823 catch (const char* msg
) {
824 dyldAPIhalt(__func__
, msg
);
830 bool _dyld_image_containing_address(const void* address
)
832 if ( dyld::gLogAPIs
)
833 dyld::log("%s(%p)\n", __func__
, address
);
834 ImageLoader
*imageLoader
= dyld::findImageContainingAddress(address
);
835 return (NULL
!= imageLoader
);
838 static NSObjectFileImage
createObjectImageFile(ImageLoader
* image
, const void* address
= NULL
, size_t len
=0)
840 NSObjectFileImage result
= new __NSObjectFileImage();
841 result
->image
= image
;
842 result
->imageBaseAddress
= address
;
843 result
->imageLength
= len
;
844 sObjectFileImages
.push_back(result
);
848 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* pathName
, NSObjectFileImage
*objectFileImage
)
850 if ( dyld::gLogAPIs
)
851 dyld::log("%s(\"%s\", ...)\n", __func__
, pathName
);
853 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
854 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
856 dyld::LoadContext context
;
857 context
.useSearchPaths
= false;
858 context
.useFallbackPaths
= false;
859 context
.useLdLibraryPath
= false;
860 context
.implicitRPath
= false;
861 context
.matchByInstallName
= false;
862 context
.dontLoad
= false;
863 context
.mustBeBundle
= true;
864 context
.mustBeDylib
= false;
865 context
.canBePIE
= false;
866 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
867 context
.rpath
= NULL
; // support not yet implemented
870 ImageLoader
* image
= dyld::load(pathName
, context
, cacheIndex
);
871 // Note: We DO NOT link the image! NSLinkModule will do that
872 if ( image
!= NULL
) {
873 if ( !image
->isBundle() ) {
874 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
875 return NSObjectFileImageInappropriateFile
;
877 *objectFileImage
= createObjectImageFile(image
);
878 return NSObjectFileImageSuccess
;
881 catch (const char* msg
) {
882 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
883 dyld::garbageCollectImages();
885 return NSObjectFileImageInappropriateFile
;
887 return NSObjectFileImageFailure
;
891 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* address
, size_t size
, NSObjectFileImage
*objectFileImage
)
893 if ( dyld::gLogAPIs
)
894 dyld::log("%s(%p, %lu, %p)\n", __func__
, address
, size
, objectFileImage
);
897 ImageLoader
* image
= dyld::loadFromMemory((const uint8_t*)address
, size
, NULL
);
898 if ( ! image
->isBundle() ) {
899 // this API can only be used with bundles...
900 dyld::garbageCollectImages();
901 return NSObjectFileImageInappropriateFile
;
903 // Note: We DO NOT link the image! NSLinkModule will do that
904 if ( image
!= NULL
) {
905 *objectFileImage
= createObjectImageFile(image
, address
, size
);
906 return NSObjectFileImageSuccess
;
909 catch (const char* msg
) {
911 dyld::garbageCollectImages();
912 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
914 return NSObjectFileImageFailure
;
917 static bool validOFI(NSObjectFileImage objectFileImage
)
919 const size_t ofiCount
= sObjectFileImages
.size();
920 for (size_t i
=0; i
< ofiCount
; ++i
) {
921 if ( sObjectFileImages
[i
] == objectFileImage
)
927 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage
)
929 if ( dyld::gLogAPIs
)
930 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
932 if ( validOFI(objectFileImage
) ) {
933 // a failure during NSLinkModule will delete the image
934 if ( objectFileImage
->image
!= NULL
) {
935 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
936 // and we should delete it
937 bool linkedImage
= dyld::validImage(objectFileImage
->image
);
938 if ( ! linkedImage
) {
939 ImageLoader::deleteImage(objectFileImage
->image
);
940 objectFileImage
->image
= NULL
;
944 // remove from list of ofi's
945 for (std::vector
<NSObjectFileImage
>::iterator it
=sObjectFileImages
.begin(); it
!= sObjectFileImages
.end(); it
++) {
946 if ( *it
== objectFileImage
) {
947 sObjectFileImages
.erase(it
);
952 // if object was created from a memory, release that memory
953 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
954 if ( objectFileImage
->imageBaseAddress
!= NULL
) {
956 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 6) ) {
957 size_t sz
= (*dyld::gLibSystemHelpers
->malloc_size
)(objectFileImage
->imageBaseAddress
);
959 (*dyld::gLibSystemHelpers
->free
)((void*)(objectFileImage
->imageBaseAddress
));
964 vm_deallocate(mach_task_self(), (vm_address_t
)objectFileImage
->imageBaseAddress
, objectFileImage
->imageLength
);
968 delete objectFileImage
;
975 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
977 if ( dyld::gLogAPIs
)
978 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
979 return objectFileImage
->image
->getExportedSymbolCount();
982 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
984 if ( dyld::gLogAPIs
)
985 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
986 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedExportedSymbol(ordinal
);
987 return objectFileImage
->image
->getExportedSymbolName(sym
);
990 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
992 if ( dyld::gLogAPIs
)
993 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
994 return objectFileImage
->image
->getImportedSymbolCount();
997 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
,
998 bool* tentative_definition
)
1000 if ( dyld::gLogAPIs
)
1001 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
1002 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedImportedSymbol(ordinal
);
1003 if ( tentative_definition
!= NULL
) {
1004 ImageLoader::ReferenceFlags flags
= objectFileImage
->image
->getImportedSymbolInfo(sym
);
1005 if ( (flags
& ImageLoader::kTentativeDefinition
) != 0 )
1006 *tentative_definition
= true;
1008 *tentative_definition
= false;
1010 return objectFileImage
->image
->getImportedSymbolName(sym
);
1013 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage
,
1014 const char* segmentName
, const char* sectionName
, unsigned long* size
)
1016 if ( dyld::gLogAPIs
)
1017 dyld::log("%s(%p,%s, %s)\n", __func__
, objectFileImage
, segmentName
, sectionName
);
1021 if ( objectFileImage
->image
->getSectionContent(segmentName
, sectionName
, &start
, &length
) ) {
1031 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage
, const char* symbolName
)
1033 if ( dyld::gLogAPIs
)
1034 dyld::log("%s(%p,%s)\n", __func__
, objectFileImage
, symbolName
);
1035 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->findExportedSymbol(symbolName
, true, NULL
);
1036 return ( sym
!= NULL
);
1041 NSModule
NSLinkModule(NSObjectFileImage objectFileImage
, const char* moduleName
, uint32_t options
)
1043 if ( dyld::gLogAPIs
)
1044 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, objectFileImage
, moduleName
, options
);
1046 dyld::clearErrorMessage();
1048 if ( (options
& NSLINKMODULE_OPTION_CAN_UNLOAD
) != 0 )
1049 objectFileImage
->image
->setCanUnload();
1051 // NSLinkModule allows a bundle to be link multpile times
1052 // each link causes the bundle to be copied to a new address
1053 if ( objectFileImage
->image
->isLinked() ) {
1054 // already linked, so clone a new one and link it
1055 objectFileImage
->image
= dyld::cloneImage(objectFileImage
->image
);
1058 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
1059 if ( objectFileImage
->image
->getPath() == NULL
) {
1060 objectFileImage
->image
->setPath(moduleName
);
1061 // <rdar://problem/8812589> dyld has NULL paths in image info array
1062 dyld_image_info info
;
1063 info
.imageLoadAddress
= objectFileImage
->image
->machHeader();
1064 info
.imageFilePath
= moduleName
;
1065 info
.imageFileModDate
= 0;
1066 addImagesToAllImages(1, &info
);
1069 // support private bundles
1070 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1071 objectFileImage
->image
->setHideExports();
1073 // set up linking options
1074 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1076 // load libraries, rebase, bind, to make this image usable
1077 dyld::link(objectFileImage
->image
, forceLazysBound
, false, ImageLoader::RPathChain(NULL
,NULL
), UINT32_MAX
);
1079 // bump reference count to keep this bundle from being garbage collected
1080 objectFileImage
->image
->incrementDlopenReferenceCount();
1082 // run initializers unless magic flag says not to
1083 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1084 dyld::runInitializers(objectFileImage
->image
);
1086 return ImageLoaderToNSModule(objectFileImage
->image
);
1088 catch (const char* msg
) {
1089 dyld::garbageCollectImages();
1090 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1091 dyldAPIhalt(__func__
, msg
);
1092 // not halting, so set error state for NSLinkEditError to find
1093 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1094 // dyld::link() deleted the image so lose our reference
1095 objectFileImage
->image
= NULL
;
1102 #if OLD_LIBSYSTEM_SUPPORT
1103 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1104 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
)
1106 if ( dyld::gLogAPIs
)
1107 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr
, moduleName
, options
); // note name/args translation
1108 ImageLoader
* image
= NULL
;
1109 dyld::clearErrorMessage();
1111 const char* imageName
= moduleName
;
1112 image
= dyld::loadFromMemory((const uint8_t*)object_addr
, object_size
, imageName
);
1114 if ( image
!= NULL
) {
1115 // support private bundles
1116 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1117 image
->setHideExports();
1119 // set up linking options
1120 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1122 // load libraries, rebase, bind, to make this image usable
1123 dyld::link(image
, forceLazysBound
, false, ImageLoader::RPathChain(NULL
,NULL
), UINT32_MAX
);
1125 // run initializers unless magic flag says not to
1126 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1127 dyld::runInitializers(image
);
1130 catch (const char* msg
) {
1131 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1132 dyldAPIhalt("NSLinkModule", msg
);
1133 // not halting, so set error state for NSLinkEditError to find
1134 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1135 // if image was created for this bundle, destroy it
1136 if ( image
!= NULL
) {
1137 dyld::removeImage(image
);
1138 ImageLoader::deleteImage(image
);
1143 return ImageLoaderToNSModule(image
);
1147 NSSymbol
NSLookupSymbolInModule(NSModule
module, const char* symbolName
)
1149 if ( dyld::gLogAPIs
)
1150 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)module, symbolName
);
1151 ImageLoader
* image
= NSModuleToImageLoader(module);
1152 if ( image
== NULL
)
1154 return SymbolToNSSymbol(image
->findExportedSymbol(symbolName
, false, NULL
));
1157 const char* NSNameOfModule(NSModule
module)
1159 if ( dyld::gLogAPIs
)
1160 dyld::log("%s(%p)\n", __func__
, module);
1161 ImageLoader
* image
= NSModuleToImageLoader(module);
1162 if ( image
== NULL
)
1164 return image
->getPath();
1167 const char* NSLibraryNameForModule(NSModule
module)
1169 if ( dyld::gLogAPIs
)
1170 dyld::log("%s(%p)\n", __func__
, module);
1171 ImageLoader
* image
= NSModuleToImageLoader(module);
1172 if ( image
== NULL
)
1174 return image
->getPath();
1177 bool NSUnLinkModule(NSModule
module, uint32_t options
)
1179 if ( dyld::gLogAPIs
)
1180 dyld::log("%s(%p, 0x%08X)\n", __func__
, module, options
);
1181 if ( module == NULL
)
1183 ImageLoader
* image
= NSModuleToImageLoader(module);
1184 if ( image
== NULL
)
1186 dyld::runImageStaticTerminators(image
);
1187 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 13) ) {
1188 __cxa_range_t ranges
[image
->segmentCount()];
1190 for (unsigned int j
=0; j
< image
->segmentCount(); ++j
) {
1191 if ( !image
->segExecutable(j
) )
1193 ranges
[rangeCount
].addr
= (const void*)image
->segActualLoadAddress(j
);
1194 ranges
[rangeCount
].length
= image
->segSize(j
);
1197 (*dyld::gLibSystemHelpers
->cxa_finalize_ranges
)(ranges
, rangeCount
);
1199 dyld::removeImage(image
);
1201 if ( (options
& NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
) != 0 )
1202 image
->setLeaveMapped();
1204 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1206 // Only delete image if there is no ofi referencing it
1207 // That means the ofi was destroyed after linking, so no one is left to delete this image
1208 const size_t ofiCount
= sObjectFileImages
.size();
1210 for (size_t i
=0; i
< ofiCount
; ++i
) {
1211 NSObjectFileImage ofi
= sObjectFileImages
[i
];
1212 if ( ofi
->image
== image
)
1216 ImageLoader::deleteImage(image
);
1221 // internal name and parameters do not match public name and parameters...
1222 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
)
1224 if ( dyld::gLogAPIs
)
1225 dyld::log("NSLinkEditErrorHandlers()\n");
1227 dyld::registerUndefinedHandler((dyld::UndefinedHandler
)undefined
);
1228 // no support for multiple or linkedit handlers
1234 void NSLinkEditError(NSLinkEditErrors
* c
, int* errorNumber
, const char** fileName
, const char** errorString
)
1237 *c
= sLastErrorFileCode
;
1238 *errorNumber
= sLastErrorNo
;
1239 *fileName
= sLastErrorFilePath
;
1240 *errorString
= dyld::getErrorMessage();
1245 static void _dyld_register_binding_handler(void * (*bindingHandler
)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions
)
1247 if ( dyld::gLogAPIs
)
1248 dyld::log("%s()\n", __func__
);
1249 dyld::gLinkContext
.bindingHandler
= bindingHandler
;
1250 dyld::gLinkContext
.bindingOptions
= bindingOptions
;
1253 #endif //DEPRECATED_APIS_SUPPORTED
1256 // Call by fork() in libSystem after the kernel trap is done on the child side
1257 void _dyld_fork_child()
1259 if ( dyld::gLogAPIs
)
1260 dyld::log("%s()\n", __func__
);
1261 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1262 // in libSystem for the child of a fork. But dyld is built with a static copy
1263 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1265 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1266 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1268 extern mach_port_t mach_task_self_
;
1269 mach_task_self_
= task_self_trap();
1271 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1272 // page is not copied on fork. <rdar://problem/6797342>
1273 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1274 dyld::gProcessInfo
->coreSymbolicationShmPage
= NULL
;
1275 // for safety, make sure child starts with clean systemOrderFlag
1276 dyld::gProcessInfo
->systemOrderFlag
= 0;
1280 #if DEPRECATED_APIS_SUPPORTED
1281 // returns true if prebinding was used in main executable
1282 bool _dyld_launched_prebound()
1284 if ( dyld::gLogAPIs
)
1285 dyld::log("%s()\n", __func__
);
1287 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1288 return dyld::mainExecutablePrebound();
1293 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1294 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1295 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1296 // flag on the image for this module. If the module was found and it was
1297 // private then everything worked and TRUE is returned else FALSE is returned.
1299 static bool NSMakePrivateModulePublic(NSModule
module)
1301 ImageLoader
* image
= NSModuleToImageLoader(module);
1302 if ( image
!= NULL
) {
1303 if ( image
->hasHiddenExports() ) {
1304 image
->setHideExports(false);
1311 #endif // DEPRECATED_APIS_SUPPORTED
1313 int _dyld_func_lookup(const char* name
, void** address
)
1315 for (const dyld_func
* p
= dyld_funcs
; p
->name
!= NULL
; ++p
) {
1316 if ( strcmp(p
->name
, name
) == 0 ) {
1317 if( p
->implementation
== unimplemented
)
1318 dyld::log("unimplemented dyld function: %s\n", p
->name
);
1319 *address
= p
->implementation
;
1328 static void registerThreadHelpers(const dyld::LibSystemHelpers
* helpers
)
1330 dyld::gLibSystemHelpers
= helpers
;
1332 #if !SUPPORT_ZERO_COST_EXCEPTIONS
1333 if ( helpers
->version
>= 5 ) {
1334 // create key use by dyld exception handling
1336 int result
= helpers
->pthread_key_create(&key
, NULL
);
1338 __Unwind_SjLj_SetThreadKey(key
);
1344 static void dlerrorClear()
1346 if ( dyld::gLibSystemHelpers
!= NULL
) {
1347 // <rdar://problem/10595338> dlerror buffer leak
1348 // dlerrorClear() should not force allocation, but zero it if already allocated
1349 if ( dyld::gLibSystemHelpers
->version
>= 10 ) {
1350 if ( ! (*dyld::gLibSystemHelpers
->hasPerThreadBufferFor_dlerror
)() )
1354 // first char of buffer is flag whether string (starting at second char) is valid
1355 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1361 static void dlerrorSet(const char* msg
)
1363 if ( dyld::gLibSystemHelpers
!= NULL
) {
1364 // first char of buffer is flag whether string (starting at second char) is valid
1365 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(strlen(msg
)+2);
1367 strcpy(&buffer
[1], msg
);
1372 bool dlopen_preflight_internal(const char* path
, void* callerAddress
)
1374 if ( dyld::gLogAPIs
)
1375 dyld::log("%s(%s)\n", __func__
, path
);
1379 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
1381 const bool leafName
= (strchr(path
, '/') == NULL
);
1382 const bool absolutePath
= (path
[0] == '/');
1383 #if TARGET_OS_IPHONE
1384 char canonicalPath
[PATH_MAX
];
1385 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1387 // make path canonical if it contains a // or ./
1388 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1389 const char* lastSlash
= strrchr(path
, '/');
1390 char dirPath
[PATH_MAX
];
1391 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1392 dirPath
[lastSlash
-path
] = '\0';
1393 if ( realpath(dirPath
, canonicalPath
) ) {
1394 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1395 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1396 // if all fit in buffer, use new canonical path
1397 path
= canonicalPath
;
1404 #if SUPPORT_ACCELERATE_TABLES
1405 if ( dyld::isPathInCache(path
) )
1409 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1410 // if requested path is to something in the dyld shared cache, always succeed
1411 if ( dyld::inSharedCache(path
) )
1415 // <rdar://problem/47464387> dlopen_preflight() on symlink to image in shared cache leaves it half loaded
1416 if ( strncmp(path
, "/System/Library/", 16) == 0 ) {
1417 char canonicalPath
[PATH_MAX
];
1418 if ( realpath(path
, canonicalPath
) ) {
1419 if ( dyld::inSharedCache(canonicalPath
) )
1425 bool result
= false;
1426 std::vector
<const char*> rpathsFromCallerImage
;
1428 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1429 // for dlopen, use rpath from caller image and from main executable
1430 if ( callerImage
!= NULL
)
1431 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1432 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1433 if ( callerImage
!= dyld::mainExecutable() ) {
1434 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1437 ImageLoader
* image
= NULL
;
1438 dyld::LoadContext context
;
1439 context
.useSearchPaths
= true;
1440 context
.useFallbackPaths
= leafName
; // a partial path implies don't use fallback paths
1441 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1442 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1443 context
.matchByInstallName
= true;
1444 context
.dontLoad
= false;
1445 context
.mustBeBundle
= false;
1446 context
.mustBeDylib
= false;
1447 context
.canBePIE
= true;
1448 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1449 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1451 unsigned cacheIndex
;
1452 image
= load(path
, context
, cacheIndex
);
1453 if ( image
!= NULL
) {
1454 dyld::preflight(image
, callersRPaths
, cacheIndex
); // image object deleted by dyld::preflight()
1458 catch (const char* msg
) {
1459 const char* str
= dyld::mkstringf("dlopen_preflight(%s): %s", path
, msg
);
1462 free((void*)msg
); // our free() will do nothing if msg is a string literal
1464 // free rpaths (getRPaths() malloc'ed each string)
1465 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1466 const char* str
= *it
;
1469 CRSetCrashLogMessage(NULL
);
1473 #if SUPPORT_ACCELERATE_TABLES
1474 bool static callerIsNonOSApp(void* callerAddress
, const char** shortName
)
1477 const mach_header
* unusedMh
;
1478 const char* unusedPath
;
1479 unsigned unusedIndex
;
1480 // any address in shared cache is not from app
1481 if ( dyld::addressInCache(callerAddress
, &unusedMh
, &unusedPath
, &unusedIndex
) )
1484 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1485 if ( callerImage
== NULL
)
1488 *shortName
= callerImage
->getShortName();
1489 return ( strncmp(callerImage
->getPath(), "/var/containers/", 16) == 0 );
1493 void* dlopen_internal(const char* path
, int mode
, void* callerAddress
)
1495 if ( dyld::gLogAPIs
)
1496 dyld::log("%s(%s, 0x%08X)\n", __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1498 #if SUPPORT_ACCELERATE_TABLES
1499 if ( dyld::gLogAppAPIs
) {
1500 const char* shortName
;
1501 if ( callerIsNonOSApp(callerAddress
, &shortName
) ) {
1502 dyld::log("%s: %s(%s, 0x%08X)\n", shortName
, __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1509 // passing NULL for path means return magic object
1510 if ( path
== NULL
) {
1511 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1512 if ( (mode
& RTLD_FIRST
) != 0 )
1513 return RTLD_MAIN_ONLY
;
1515 return RTLD_DEFAULT
;
1518 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1519 bool lockHeld
= false;
1520 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 4) ) {
1521 dyld::gLibSystemHelpers
->acquireGlobalDyldLock();
1522 CRSetCrashLogMessage("dyld: in dlopen()");
1526 void* result
= NULL
;
1527 const bool leafName
= (strchr(path
, '/') == NULL
);
1528 const bool absolutePath
= (path
[0] == '/');
1529 #if TARGET_OS_IPHONE
1530 char canonicalPath
[PATH_MAX
];
1531 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1533 // make path canonical if it contains a // or ./
1534 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1535 const char* lastSlash
= strrchr(path
, '/');
1536 char dirPath
[PATH_MAX
];
1537 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1538 dirPath
[lastSlash
-path
] = '\0';
1539 if ( realpath(dirPath
, canonicalPath
) ) {
1540 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1541 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1542 // if all fit in buffer, use new canonical path
1543 path
= canonicalPath
;
1550 #if SUPPORT_ACCELERATE_TABLES
1551 if ( dyld::dlopenFromCache(path
, mode
, &result
) ) {
1552 // Note: dlopenFromCache() releases the lock
1553 if ( dyld::gLogAPIs
)
1554 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1559 ImageLoader
* image
= NULL
;
1560 std::vector
<const char*> rpathsFromCallerImage
;
1561 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1563 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1564 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1565 // for dlopen, use rpath from caller image and from main executable
1566 if ( callerImage
!= NULL
)
1567 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1568 if ( callerImage
!= dyld::mainExecutable() )
1569 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1572 dyld::LoadContext context
;
1573 context
.useSearchPaths
= true;
1574 context
.useFallbackPaths
= leafName
; // a partial path means no fallback paths
1575 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1576 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1577 context
.matchByInstallName
= true;
1578 context
.dontLoad
= ( (mode
& RTLD_NOLOAD
) != 0 );
1579 context
.mustBeBundle
= false;
1580 context
.mustBeDylib
= false;
1581 context
.canBePIE
= true;
1582 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1583 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1585 unsigned cacheIndex
;
1586 image
= load(path
, context
, cacheIndex
);
1587 #if SUPPORT_ACCELERATE_TABLES
1588 if ( (image
!= NULL
) && (cacheIndex
!= UINT32_MAX
) ) {
1589 // found in cache, but under a different path
1590 const char* betterPath
= dyld::getPathFromIndex(cacheIndex
);
1591 if ( (betterPath
!= NULL
) && dyld::dlopenFromCache(betterPath
, mode
, &result
) ) {
1592 // Note: dlopenFromCache() releases the lock
1593 if ( dyld::gLogAPIs
)
1594 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1599 if ( image
!= NULL
) {
1600 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1601 // this image is not garbage collected
1602 image
->incrementDlopenReferenceCount();
1603 // link in all dependents
1604 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1605 bool alreadyLinked
= image
->isLinked();
1606 bool forceLazysBound
= ( (mode
& RTLD_NOW
) != 0 );
1607 dyld::link(image
, forceLazysBound
, false, callersRPaths
, cacheIndex
);
1608 if ( alreadyLinked
) {
1610 if ( ((mode
& RTLD_LOCAL
) == 0) && image
->hasHiddenExports() )
1611 image
->setHideExports(false);
1614 // only hide exports if image is not already in use
1615 if ( (mode
& RTLD_LOCAL
) != 0 )
1616 image
->setHideExports(true);
1620 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1621 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1622 // The subtle differences are:
1623 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1624 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1625 if ( (mode
& RTLD_NODELETE
) != 0 )
1626 image
->setLeaveMapped();
1628 // release global dyld lock early, this enables initializers to do threaded operations
1630 CRSetCrashLogMessage(NULL
);
1631 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1635 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1636 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1637 // called from within an initializer because it can cause initializers to run
1638 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1639 // to run, then don't use RTLD_NOLOAD.
1640 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1642 dyld::runInitializers(image
);
1645 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1646 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1647 if ( (mode
& RTLD_FIRST
) != 0 )
1648 result
= (void*)(((uintptr_t)image
)|1);
1653 catch (const char* msg
) {
1654 if ( image
!= NULL
) {
1655 // load() succeeded but, link() failed
1656 // back down reference count and do GC
1657 image
->decrementDlopenReferenceCount();
1658 if ( image
->dlopenCount() == 0 )
1659 dyld::garbageCollectImages();
1661 const char* str
= dyld::mkstringf("dlopen(%s, %d): %s", path
, mode
, msg
);
1662 if ( dyld::gLogAPIs
)
1663 dyld::log(" %s() failed, error: '%s'\n", __func__
, str
);
1666 free((void*)msg
); // our free() will do nothing if msg is a string literal
1669 // free rpaths (getRPaths() malloc'ed each string)
1670 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1671 const char* str
= *it
;
1675 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1676 if ( (mode
& RTLD_NOLOAD
) && (result
== NULL
) ) {
1677 dlerrorSet("image not already loaded");
1681 CRSetCrashLogMessage(NULL
);
1682 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1684 if ( dyld::gLogAPIs
&& (result
!= NULL
) )
1685 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1689 int dlclose(void* handle
)
1691 if ( dyld::gLogAPIs
)
1692 dyld::log("%s(%p)\n", __func__
, handle
);
1694 // silently accept magic handles for main executable
1695 if ( handle
== RTLD_MAIN_ONLY
)
1697 if ( handle
== RTLD_DEFAULT
)
1700 #if SUPPORT_ACCELERATE_TABLES
1701 if ( dyld::isCacheHandle(handle
) ) {
1707 ImageLoader
* image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1708 if ( dyld::validImage(image
) ) {
1710 // decrement use count
1711 if ( image
->decrementDlopenReferenceCount() ) {
1712 dlerrorSet("dlclose() called too many times");
1715 // remove image if reference count went to zero
1716 if ( image
->dlopenCount() == 0 )
1717 dyld::garbageCollectImages();
1721 dlerrorSet("invalid handle passed to dlclose()");
1728 int dladdr(const void* address
, Dl_info
* info
)
1730 if ( dyld::gLogAPIs
)
1731 dyld::log("%s(%p, %p)\n", __func__
, address
, info
);
1733 // <rdar://problem/42171466> calling dladdr(xx,NULL) crashes
1735 return 0; // failure
1737 address
= stripPointer(address
);
1739 CRSetCrashLogMessage("dyld: in dladdr()");
1740 #if SUPPORT_ACCELERATE_TABLES
1741 if ( dyld::dladdrFromCache(address
, info
) ) {
1742 CRSetCrashLogMessage(NULL
);
1743 return 1; // success
1747 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1748 if ( image
!= NULL
) {
1749 info
->dli_fname
= image
->getRealPath();
1750 info
->dli_fbase
= (void*)image
->machHeader();
1751 if ( address
== info
->dli_fbase
) {
1752 // special case lookup of header
1753 info
->dli_sname
= "__dso_handle";
1754 info
->dli_saddr
= info
->dli_fbase
;
1755 CRSetCrashLogMessage(NULL
);
1756 return 1; // success
1758 // find closest symbol in the image
1759 info
->dli_sname
= image
->findClosestSymbol(address
, (const void**)&info
->dli_saddr
);
1760 // never return the mach_header symbol
1761 if ( info
->dli_saddr
== info
->dli_fbase
) {
1762 info
->dli_sname
= NULL
;
1763 info
->dli_saddr
= NULL
;
1764 CRSetCrashLogMessage(NULL
);
1765 return 1; // success
1767 if ( info
->dli_sname
!= NULL
) {
1768 if ( info
->dli_sname
[0] == '_' )
1769 info
->dli_sname
= info
->dli_sname
+1; // strip off leading underscore
1770 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1771 CRSetCrashLogMessage(NULL
);
1772 return 1; // success
1774 info
->dli_sname
= NULL
;
1775 info
->dli_saddr
= NULL
;
1776 CRSetCrashLogMessage(NULL
);
1777 return 1; // success
1779 CRSetCrashLogMessage(NULL
);
1780 return 0; // failure
1786 if ( dyld::gLogAPIs
)
1787 dyld::log("%s()\n", __func__
);
1789 if ( dyld::gLibSystemHelpers
!= NULL
) {
1790 // if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
1791 if ( dyld::gLibSystemHelpers
->version
>= 10 ) {
1792 if ( ! (*dyld::gLibSystemHelpers
->hasPerThreadBufferFor_dlerror
)() )
1796 // first char of buffer is flag whether string (starting at second char) is valid
1797 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1798 if ( buffer
[0] != '\0' ) { // if valid buffer
1799 buffer
[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1800 return &buffer
[1]; // return message
1806 void* dlsym_internal(void* handle
, const char* symbolName
, void* callerAddress
)
1808 if ( dyld::gLogAPIs
)
1809 dyld::log("%s(%p, %s)\n", __func__
, handle
, symbolName
);
1811 #if SUPPORT_ACCELERATE_TABLES
1812 if ( dyld::gLogAppAPIs
) {
1813 const char* shortName
;
1814 if ( callerIsNonOSApp(callerAddress
, &shortName
) ) {
1815 dyld::log("%s: %s(%p, %s)\n", shortName
, __func__
, handle
, symbolName
);
1820 CRSetCrashLogMessage("dyld: in dlsym()");
1823 const ImageLoader
* image
;
1824 const ImageLoader::Symbol
* sym
;
1827 // dlsym() assumes symbolName passed in is same as in C source code
1828 // dyld assumes all symbol names have an underscore prefix
1829 char underscoredName
[strlen(symbolName
)+2];
1830 underscoredName
[0] = '_';
1831 strcpy(&underscoredName
[1], symbolName
);
1833 // magic "search all" handle
1834 if ( handle
== RTLD_DEFAULT
) {
1835 if ( dyld::flatFindExportedSymbol(underscoredName
, &sym
, &image
) ) {
1836 CRSetCrashLogMessage(NULL
);
1837 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, NULL
, false, underscoredName
);
1838 #if __has_feature(ptrauth_calls)
1839 // Sign the pointer if it points to a function
1840 // Note we only do this if the main executable is arm64e as otherwise we
1841 // may end up calling containsAddress on the accelerator tables.
1842 if ( result
&& ((dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
& ~CPU_SUBTYPE_MASK
) == CPU_SUBTYPE_ARM64E
) ) {
1843 const ImageLoader
* symbolImage
= image
;
1844 if (!symbolImage
->containsAddress(result
)) {
1845 symbolImage
= dyld::findImageContainingAddress(result
);
1847 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
1848 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
1849 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
1852 if ( dyld::gLogAPIs
)
1853 dyld::log(" %s(RTLD_DEFAULT, %s) ==> %p\n", __func__
, symbolName
, result
);
1856 const char* str
= dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName
);
1859 CRSetCrashLogMessage(NULL
);
1860 if ( dyld::gLogAPIs
)
1861 dyld::log(" %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__
, symbolName
);
1865 // magic "search only main executable" handle
1866 else if ( handle
== RTLD_MAIN_ONLY
) {
1867 image
= dyld::mainExecutable();
1868 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1869 if ( sym
!= NULL
) {
1870 CRSetCrashLogMessage(NULL
);
1871 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, NULL
, false, underscoredName
);
1872 #if __has_feature(ptrauth_calls)
1873 // Sign the pointer if it points to a function
1874 // Note we only do this if the main executable is arm64e as otherwise we
1875 // may end up calling containsAddress on the accelerator tables.
1876 if ( result
&& ((dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
& ~CPU_SUBTYPE_MASK
) == CPU_SUBTYPE_ARM64E
) ) {
1877 const ImageLoader
* symbolImage
= image
;
1878 if (!symbolImage
->containsAddress(result
)) {
1879 symbolImage
= dyld::findImageContainingAddress(result
);
1881 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
1882 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
1883 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
1886 if ( dyld::gLogAPIs
)
1887 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__
, symbolName
, result
);
1890 const char* str
= dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName
);
1893 CRSetCrashLogMessage(NULL
);
1894 if ( dyld::gLogAPIs
)
1895 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__
, symbolName
);
1899 // magic "search what I would see" handle
1900 else if ( handle
== RTLD_NEXT
) {
1901 #if SUPPORT_ACCELERATE_TABLES
1902 const mach_header
* mh
;
1905 if ( dyld::addressInCache(callerAddress
, &mh
, &path
, &index
) ) {
1906 // if dylib in cache is calling dlsym(RTLD_NEXT,xxx) handle search differently
1907 result
= dyld::dlsymFromCache(RTLD_NEXT
, underscoredName
, index
);
1908 if ( dyld::gLogAPIs
)
1909 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1913 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1914 sym
= callerImage
->findExportedSymbolInDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // don't search image, but do search what it links against
1915 if ( sym
!= NULL
) {
1916 CRSetCrashLogMessage(NULL
);
1917 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1918 #if __has_feature(ptrauth_calls)
1919 // Sign the pointer if it points to a function
1920 // Note we only do this if the main executable is arm64e as otherwise we
1921 // may end up calling containsAddress on the accelerator tables.
1922 if ( result
&& ((dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
& ~CPU_SUBTYPE_MASK
) == CPU_SUBTYPE_ARM64E
) ) {
1923 const ImageLoader
* symbolImage
= image
;
1924 if (!symbolImage
->containsAddress(result
)) {
1925 symbolImage
= dyld::findImageContainingAddress(result
);
1927 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
1928 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
1929 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
1932 if ( dyld::gLogAPIs
)
1933 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1936 const char* str
= dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName
);
1939 CRSetCrashLogMessage(NULL
);
1940 if ( dyld::gLogAPIs
)
1941 dyld::log(" %s(RTLD_NEXT, %s) ==> NULL\n", __func__
, symbolName
);
1944 // magic "search me, then what I would see" handle
1945 else if ( handle
== RTLD_SELF
) {
1946 #if SUPPORT_ACCELERATE_TABLES
1947 const mach_header
* mh
;
1950 if ( dyld::addressInCache(callerAddress
, &mh
, &path
, &index
) ) {
1951 // if dylib in cache is calling dlsym(RTLD_SELF,xxx) handle search differently
1952 result
= dyld::dlsymFromCache(RTLD_SELF
, underscoredName
, index
);
1953 if ( dyld::gLogAPIs
)
1954 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1958 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1959 sym
= callerImage
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1960 if ( sym
!= NULL
) {
1961 CRSetCrashLogMessage(NULL
);
1962 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1963 #if __has_feature(ptrauth_calls)
1964 // Sign the pointer if it points to a function
1965 // Note we only do this if the main executable is arm64e as otherwise we
1966 // may end up calling containsAddress on the accelerator tables.
1967 if ( result
&& ((dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
& ~CPU_SUBTYPE_MASK
) == CPU_SUBTYPE_ARM64E
) ) {
1968 const ImageLoader
* symbolImage
= image
;
1969 if (!symbolImage
->containsAddress(result
)) {
1970 symbolImage
= dyld::findImageContainingAddress(result
);
1972 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
1973 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
1974 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
1977 if ( dyld::gLogAPIs
)
1978 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1981 const char* str
= dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName
);
1984 CRSetCrashLogMessage(NULL
);
1985 if ( dyld::gLogAPIs
)
1986 dyld::log(" %s(RTLD_SELF, %s) ==> NULL\n", __func__
, symbolName
);
1989 #if SUPPORT_ACCELERATE_TABLES
1990 // check for mega dylib handle
1991 else if ( dyld::isCacheHandle(handle
) ) {
1992 result
= dyld::dlsymFromCache(handle
, underscoredName
, 0);
1993 if ( dyld::gLogAPIs
)
1994 dyld::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
1999 image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
2000 if ( dyld::validImage(image
) ) {
2001 if ( (((uintptr_t)handle
) & 1) != 0 )
2002 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
2004 sym
= image
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
2006 if ( sym
!= NULL
) {
2007 CRSetCrashLogMessage(NULL
);
2008 ImageLoader
* callerImage
= NULL
;
2009 if ( sDynamicInterposing
) {
2010 // only take time to look up caller, if dynamic interposing in use
2011 callerImage
= dyld::findImageContainingAddress(callerAddress
);
2013 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
2014 #if __has_feature(ptrauth_calls)
2015 // Sign the pointer if it points to a function
2016 // Note we only do this if the main executable is arm64e as otherwise we
2017 // may end up calling containsAddress on the accelerator tables.
2018 if ( result
&& ((dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
& ~CPU_SUBTYPE_MASK
) == CPU_SUBTYPE_ARM64E
) ) {
2019 const ImageLoader
* symbolImage
= image
;
2020 if (!symbolImage
->containsAddress(result
)) {
2021 symbolImage
= dyld::findImageContainingAddress(result
);
2023 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
2024 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
2025 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
2028 if ( dyld::gLogAPIs
)
2029 dyld::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
2032 const char* str
= dyld::mkstringf("dlsym(%p, %s): symbol not found", handle
, symbolName
);
2037 dlerrorSet("invalid handle passed to dlsym()");
2039 CRSetCrashLogMessage(NULL
);
2040 if ( dyld::gLogAPIs
)
2041 dyld::log(" %s(%p, %s) ==> NULL\n", __func__
, handle
, symbolName
);
2045 // Note this is only here to support ___pthread_abort in libpthread.a
2046 void* dlsym(void* handle
, const char* symbolName
) {
2047 return dlsym_internal(handle
, symbolName
, __builtin_return_address(1));
2051 // <rdar://problem/40352925> *_compat functions are for old binaries that have __dyld section and use it to bypass libdyld.dylib
2052 void* dlopen_compat(const char* path
, int mode
)
2054 return dlopen_internal(path
, mode
, (void*)dyld::mainExecutable()->machHeader());
2056 bool dlopen_preflight_compat(const char* path
)
2058 return dlopen_preflight_internal(path
, (void*)dyld::mainExecutable()->machHeader());
2060 void* dlsym_compat(void* handle
, const char* symbolName
)
2062 return dlsym_internal(handle
, symbolName
, (void*)dyld::mainExecutable()->machHeader());
2068 const struct dyld_all_image_infos
* _dyld_get_all_image_infos()
2070 return dyld::gProcessInfo
;
2074 #if SUPPORT_ZERO_COST_EXCEPTIONS
2075 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
)
2077 //if ( dyld::gLogAPIs )
2078 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
2080 addr
= stripPointer(addr
);
2082 #if SUPPORT_ACCELERATE_TABLES
2083 if ( dyld::findUnwindSections(addr
, info
) )
2086 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
2087 if ( image
!= NULL
) {
2088 image
->getUnwindInfo(info
);
2096 const char* dyld_image_path_containing_address(const void* address
)
2098 if ( dyld::gLogAPIs
)
2099 dyld::log("%s(%p)\n", __func__
, address
);
2101 address
= (void*)stripPointer(address
);
2103 #if SUPPORT_ACCELERATE_TABLES
2104 const mach_header
* mh
;
2106 if ( dyld::addressInCache(address
, &mh
, &path
) )
2110 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
2111 if ( image
!= NULL
) {
2112 return image
->getRealPath();
2119 bool dyld_shared_cache_some_image_overridden()
2121 return dyld::gSharedCacheOverridden
;
2125 void dyld_dynamic_interpose(const struct mach_header
* mh
, const struct dyld_interpose_tuple array
[], size_t count
)
2129 if ( array
== NULL
)
2133 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
2134 if ( image
== NULL
)
2137 // make pass at bound references in this image and update them
2138 dyld::gLinkContext
.dynamicInterposeArray
= array
;
2139 dyld::gLinkContext
.dynamicInterposeCount
= count
;
2140 image
->dynamicInterpose(dyld::gLinkContext
);
2141 dyld::gLinkContext
.dynamicInterposeArray
= NULL
;
2142 dyld::gLinkContext
.dynamicInterposeCount
= 0;
2144 // leave interposing info so any future (lazy) binding will get it too
2145 image
->addDynamicInterposingTuples(array
, count
);
2147 sDynamicInterposing
= true;
2151 bool _dyld_is_memory_immutable(const void* addr
, size_t length
)
2153 if ( dyld::gLogAPIs
)
2154 dyld::log("%s(%p, %ld)\n", __func__
, addr
, length
);
2156 uintptr_t checkStart
= (uintptr_t)addr
;
2157 uintptr_t checkEnd
= checkStart
+ length
;
2159 // quick check to see if in r/o region of shared cache. If so return true.
2160 const DyldSharedCache
* cache
= (DyldSharedCache
*)dyld::imMemorySharedCacheHeader();
2161 if ( cache
!= nullptr ) {
2162 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)((char*)cache
+ cache
->header
.mappingOffset
);
2163 uintptr_t roStart
= (uintptr_t)cache
;
2164 uintptr_t roEnd
= roStart
+ (uintptr_t)mappings
[0].size
;
2165 if ( (roStart
< checkStart
) && (checkEnd
< roEnd
) )
2169 // Otherwise find if addr is in a dyld loaded image
2170 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
2171 if ( image
!= NULL
) {
2172 // <rdar://problem/24091154> already checked for r/o portion of cache
2173 if ( image
->inSharedCache() )
2175 if ( !image
->neverUnload() )
2177 for (unsigned i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
2178 if ( (image
->segActualLoadAddress(i
) < checkStart
) && (checkEnd
< image
->segActualEndAddress(i
)) ) {
2179 return !image
->segWriteable(i
);
2188 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped
,
2189 _dyld_objc_notify_init init
,
2190 _dyld_objc_notify_unmapped unmapped
)
2192 dyld::registerObjCNotifiers(mapped
, init
, unmapped
);
2196 bool _dyld_get_shared_cache_uuid(uuid_t uuid
)
2198 return dyld::sharedCacheUUID(uuid
);
2201 const void* _dyld_get_shared_cache_range(size_t* length
)
2203 const DyldSharedCache
* cache
= (DyldSharedCache
*)dyld::imMemorySharedCacheHeader();
2204 if ( cache
!= nullptr ) {
2205 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)((char*)cache
+ cache
->header
.mappingOffset
);
2206 const dyld_cache_mapping_info
* lastMapping
= &mappings
[cache
->header
.mappingCount
- 1];
2207 *length
= (size_t)((lastMapping
->address
+ lastMapping
->size
) - cache
->unslidLoadAddress());
2213 void _dyld_images_for_addresses(unsigned count
, const void* addresses
[], struct dyld_image_uuid_offset infos
[])
2215 for (unsigned i
=0; i
< count
; ++i
) {
2216 const void* addr
= addresses
[i
];
2217 addr
= stripPointer(addr
);
2218 bzero(&infos
[i
], sizeof(dyld_image_uuid_offset
));
2219 #if SUPPORT_ACCELERATE_TABLES
2220 const mach_header
* mh
;
2222 if ( dyld::addressInCache(addr
, &mh
, &path
) ) {
2223 infos
[i
].image
= mh
;
2224 infos
[i
].offsetInImage
= (uintptr_t)addr
- (uintptr_t)mh
;
2225 ((dyld3::MachOFile
*)mh
)->getUuid(infos
[i
].uuid
);
2229 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
2230 if ( image
!= nullptr ) {
2231 infos
[i
].image
= image
->machHeader();
2232 infos
[i
].offsetInImage
= (uintptr_t)addr
- (uintptr_t)(image
->machHeader());
2233 image
->getUUID(infos
[i
].uuid
);
2238 void _dyld_register_for_image_loads(void (*func
)(const mach_header
* mh
, const char* path
, bool unloadable
))
2240 if ( dyld::gLogAPIs
)
2241 dyld::log("%s(%p)\n", __func__
, (void *)func
);
2242 dyld::registerLoadCallback(func
);
2245 void _dyld_register_for_bulk_image_loads(void (*func
)(unsigned imageCount
, const struct mach_header
* mhs
[], const char* paths
[]))
2247 if ( dyld::gLogAPIs
)
2248 dyld::log("%s(%p)\n", __func__
, (void *)func
);
2249 dyld::registerBulkLoadCallback(func
);
2252 void _dyld_register_driverkit_main(void (*mainFunc
)())
2254 dyld::setMainEntry(mainFunc
);