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()
49 #include "mach-o/dyld_images.h"
50 #include "mach-o/dyld.h"
51 #include "mach-o/dyld_priv.h"
53 #include "ImageLoader.h"
54 #include "ImageLoaderMachO.h"
56 #include "dyldLibSystemInterface.h"
57 #include "DyldSharedCache.h"
59 #undef _POSIX_C_SOURCE
63 // this was in dyld_priv.h but it is no longer exported
65 const struct dyld_all_image_infos
* _dyld_get_all_image_infos();
68 // from dyldExceptions.c
69 extern "C" void __Unwind_SjLj_SetThreadKey(pthread_key_t key
);
72 extern void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
73 extern uint32_t allImagesCount();
74 extern const mach_header
* allImagesIndexedMachHeader(uint32_t index
);
75 extern const char* allImagesIndexedPath(uint32_t index
);
77 extern "C" int _dyld_func_lookup(const char* name
, void** address
);
79 // deprecated APIs are still availble on Mac OS X, but not on iPhone OS
80 #if __IPHONE_OS_VERSION_MIN_REQUIRED
81 #define DEPRECATED_APIS_SUPPORTED 0
83 #define DEPRECATED_APIS_SUPPORTED 1
86 static bool sDynamicInterposing
= false;
88 #if DEPRECATED_APIS_SUPPORTED
89 static char sLastErrorFilePath
[1024];
90 static NSLinkEditErrors sLastErrorFileCode
;
91 static int sLastErrorNo
;
94 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
95 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
96 // This conditional keeps support for old libSystem's which needed some help implementing the API's
97 #define OLD_LIBSYSTEM_SUPPORT (__i386__)
99 // The following functions have no prototype in any header. They are special cases
100 // where _dyld_func_lookup() is used directly.
101 static void _dyld_make_delayed_module_initializer_calls();
102 static void registerThreadHelpers(const dyld::LibSystemHelpers
*);
103 #if DEPRECATED_APIS_SUPPORTED
104 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
);
105 #if OLD_LIBSYSTEM_SUPPORT
106 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
);
108 static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions
);
109 static bool NSMakePrivateModulePublic(NSModule
module);
110 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
);
112 // The following functions are dyld API's, but since dyld links with a static copy of libc.a
113 // the public name cannot be used.
114 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module);
115 static bool client_NSIsSymbolNameDefined(const char* symbolName
);
116 #endif // DEPRECATED_APIS_SUPPORTED
117 #if SUPPORT_ZERO_COST_EXCEPTIONS
118 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
);
120 #if DEPRECATED_APIS_SUPPORTED
123 static void unimplemented()
125 dyld::halt("unimplemented dyld function\n");
130 void* implementation
;
133 static struct dyld_func dyld_funcs
[] = {
134 {"__dyld_register_func_for_add_image", (void*)_dyld_register_func_for_add_image
},
135 {"__dyld_register_func_for_remove_image", (void*)_dyld_register_func_for_remove_image
},
136 {"__dyld_dladdr", (void*)dladdr
},
137 {"__dyld_dlclose", (void*)dlclose
},
138 {"__dyld_dlerror", (void*)dlerror
},
139 {"__dyld_dlopen", (void*)dlopen
},
140 {"__dyld_dlsym", (void*)dlsym
},
141 {"__dyld_dlopen_preflight", (void*)dlopen_preflight
},
142 {"__dyld_image_count", (void*)_dyld_image_count
},
143 {"__dyld_get_image_header", (void*)_dyld_get_image_header
},
144 {"__dyld_get_image_vmaddr_slide", (void*)_dyld_get_image_vmaddr_slide
},
145 {"__dyld_get_image_name", (void*)_dyld_get_image_name
},
146 {"__dyld_get_image_slide", (void*)_dyld_get_image_slide
},
147 {"__dyld__NSGetExecutablePath", (void*)_NSGetExecutablePath
},
150 {"__dyld_register_thread_helpers", (void*)registerThreadHelpers
},
151 {"__dyld_fork_child", (void*)_dyld_fork_child
},
152 {"__dyld_make_delayed_module_initializer_calls", (void*)_dyld_make_delayed_module_initializer_calls
},
153 {"__dyld_get_all_image_infos", (void*)_dyld_get_all_image_infos
},
154 #if SUPPORT_ZERO_COST_EXCEPTIONS
155 {"__dyld_find_unwind_sections", (void*)client_dyld_find_unwind_sections
},
157 #if __i386__ || __x86_64__ || __arm__ || __arm64__
158 {"__dyld_fast_stub_entry", (void*)dyld::fastBindLazySymbol
},
160 {"__dyld_image_path_containing_address", (void*)dyld_image_path_containing_address
},
161 {"__dyld_shared_cache_some_image_overridden", (void*)dyld_shared_cache_some_image_overridden
},
162 {"__dyld_process_is_restricted", (void*)dyld::processIsRestricted
},
163 {"__dyld_dynamic_interpose", (void*)dyld_dynamic_interpose
},
164 {"__dyld_shared_cache_file_path", (void*)dyld::getStandardSharedCacheFilePath
},
165 {"__dyld_get_image_header_containing_address", (void*)dyld_image_header_containing_address
},
166 {"__dyld_is_memory_immutable", (void*)_dyld_is_memory_immutable
},
167 {"__dyld_objc_notify_register", (void*)_dyld_objc_notify_register
},
168 {"__dyld_get_shared_cache_uuid", (void*)_dyld_get_shared_cache_uuid
},
169 {"__dyld_get_shared_cache_range", (void*)_dyld_get_shared_cache_range
},
173 #if DEPRECATED_APIS_SUPPORTED
174 {"__dyld_lookup_and_bind", (void*)client_dyld_lookup_and_bind
},
175 {"__dyld_lookup_and_bind_with_hint", (void*)_dyld_lookup_and_bind_with_hint
},
176 {"__dyld_lookup_and_bind_fully", (void*)_dyld_lookup_and_bind_fully
},
177 {"__dyld_install_handlers", (void*)_dyld_install_handlers
},
178 {"__dyld_link_edit_error", (void*)NSLinkEditError
},
179 {"__dyld_unlink_module", (void*)NSUnLinkModule
},
180 {"__dyld_bind_fully_image_containing_address", (void*)_dyld_bind_fully_image_containing_address
},
181 {"__dyld_image_containing_address", (void*)_dyld_image_containing_address
},
182 {"__dyld_register_binding_handler", (void*)_dyld_register_binding_handler
},
183 {"__dyld_NSNameOfSymbol", (void*)NSNameOfSymbol
},
184 {"__dyld_NSAddressOfSymbol", (void*)NSAddressOfSymbol
},
185 {"__dyld_NSModuleForSymbol", (void*)NSModuleForSymbol
},
186 {"__dyld_NSLookupAndBindSymbol", (void*)NSLookupAndBindSymbol
},
187 {"__dyld_NSLookupAndBindSymbolWithHint", (void*)NSLookupAndBindSymbolWithHint
},
188 {"__dyld_NSLookupSymbolInModule", (void*)NSLookupSymbolInModule
},
189 {"__dyld_NSLookupSymbolInImage", (void*)NSLookupSymbolInImage
},
190 {"__dyld_NSMakePrivateModulePublic", (void*)NSMakePrivateModulePublic
},
191 {"__dyld_NSIsSymbolNameDefined", (void*)client_NSIsSymbolNameDefined
},
192 {"__dyld_NSIsSymbolNameDefinedWithHint", (void*)NSIsSymbolNameDefinedWithHint
},
193 {"__dyld_NSIsSymbolNameDefinedInImage", (void*)NSIsSymbolNameDefinedInImage
},
194 {"__dyld_NSNameOfModule", (void*)NSNameOfModule
},
195 {"__dyld_NSLibraryNameForModule", (void*)NSLibraryNameForModule
},
196 {"__dyld_NSAddLibrary", (void*)NSAddLibrary
},
197 {"__dyld_NSAddLibraryWithSearching", (void*)NSAddLibraryWithSearching
},
198 {"__dyld_NSAddImage", (void*)NSAddImage
},
199 {"__dyld_launched_prebound", (void*)_dyld_launched_prebound
},
200 {"__dyld_all_twolevel_modules_prebound", (void*)_dyld_all_twolevel_modules_prebound
},
201 {"__dyld_call_module_initializers_for_dylib", (void*)_dyld_call_module_initializers_for_dylib
},
202 {"__dyld_NSCreateObjectFileImageFromFile", (void*)NSCreateObjectFileImageFromFile
},
203 {"__dyld_NSCreateObjectFileImageFromMemory", (void*)NSCreateObjectFileImageFromMemory
},
204 {"__dyld_NSDestroyObjectFileImage", (void*)NSDestroyObjectFileImage
},
205 {"__dyld_NSLinkModule", (void*)NSLinkModule
},
206 {"__dyld_NSSymbolDefinitionCountInObjectFileImage", (void*)NSSymbolDefinitionCountInObjectFileImage
},
207 {"__dyld_NSSymbolDefinitionNameInObjectFileImage", (void*)NSSymbolDefinitionNameInObjectFileImage
},
208 {"__dyld_NSIsSymbolDefinedInObjectFileImage", (void*)NSIsSymbolDefinedInObjectFileImage
},
209 {"__dyld_NSSymbolReferenceNameInObjectFileImage", (void*)NSSymbolReferenceNameInObjectFileImage
},
210 {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage
},
211 {"__dyld_NSGetSectionDataInObjectFileImage", (void*)NSGetSectionDataInObjectFileImage
},
212 #if OLD_LIBSYSTEM_SUPPORT
213 {"__dyld_link_module", (void*)_dyld_link_module
},
215 #endif //DEPRECATED_APIS_SUPPORTED
222 #if DEPRECATED_APIS_SUPPORTED
224 static void dyldAPIhalt(const char* apiName
, const char* errorMsg
)
226 dyld::log("dyld: %s() error\n", apiName
);
227 dyld::halt(errorMsg
);
230 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
231 inline NSSymbol
SymbolToNSSymbol(const ImageLoader::Symbol
* sym
)
233 return (NSSymbol
)sym
;
235 inline const ImageLoader::Symbol
* NSSymbolToSymbol(NSSymbol sym
)
237 return (const ImageLoader::Symbol
*)sym
;
240 // dyld's abstract type NSModule is implemented as ImageLoader*
241 inline NSModule
ImageLoaderToNSModule(const ImageLoader
* image
)
243 return (NSModule
)image
;
245 inline ImageLoader
* NSModuleToImageLoader(NSModule
module)
247 ImageLoader
* image
= (ImageLoader
*)module;
248 if ( dyld::validImage(image
) )
253 // actual definition for opaque type
254 struct __NSObjectFileImage
257 const void* imageBaseAddress
; // not used with OFI created from files
258 size_t imageLength
; // not used with OFI created from files
262 VECTOR_NEVER_DESTRUCTED(NSObjectFileImage
);
263 static std::vector
<NSObjectFileImage
> sObjectFileImages
;
268 // __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
269 // The contained image is delete in one of two places:
270 // NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
271 // NSDestroyObjectFileImage deletes the image if image is not in list of valid images
276 static void setLastError(NSLinkEditErrors code
, int errnum
, const char* file
, const char* message
)
278 dyld::setErrorMessage(message
);
279 strncpy(sLastErrorFilePath
, file
, 1024);
280 sLastErrorFilePath
[1023] = '\0';
281 sLastErrorFileCode
= code
;
282 sLastErrorNo
= errnum
;
285 #endif // DEPRECATED_APIS_SUPPORTED
288 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
289 * copies the path of the executable into the buffer and returns 0 if the path
290 * was successfully copied in the provided buffer. If the buffer is not large
291 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
292 * Note that _NSGetExecutablePath will return "a path" to the executable not a
293 * "real path" to the executable. That is the path may be a symbolic link and
294 * not the real file. And with deep directories the total bufsize needed could
295 * be more than MAXPATHLEN.
297 int _NSGetExecutablePath(char* buf
, uint32_t *bufsize
)
299 if ( dyld::gLogAPIs
)
300 dyld::log("%s(...)\n", __func__
);
301 const char* exePath
= dyld::getExecutablePath();
302 if(*bufsize
< strlen(exePath
) + 1){
303 *bufsize
= (uint32_t)(strlen(exePath
) + 1);
306 strcpy(buf
, exePath
);
310 uint32_t _dyld_image_count(void)
312 if ( dyld::gLogAPIs
)
313 dyld::log("%s()\n", __func__
);
314 return allImagesCount();
317 const struct mach_header
* _dyld_get_image_header(uint32_t image_index
)
319 if ( dyld::gLogAPIs
)
320 dyld::log("%s(%u)\n", __func__
, image_index
);
321 return allImagesIndexedMachHeader(image_index
);
324 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index
)
326 if ( dyld::gLogAPIs
)
327 dyld::log("%s(%u)\n", __func__
, image_index
);
328 const struct mach_header
* mh
= allImagesIndexedMachHeader(image_index
);
330 return ImageLoaderMachO::computeSlide(mh
);
335 intptr_t _dyld_get_image_slide(const struct mach_header
* mh
)
337 if ( dyld::gLogAPIs
)
338 dyld::log("%s(%p)\n", __func__
, mh
);
339 return ImageLoaderMachO::computeSlide(mh
);
343 const char* _dyld_get_image_name(uint32_t image_index
)
345 if ( dyld::gLogAPIs
)
346 dyld::log("%s(%u)\n", __func__
, image_index
);
347 return allImagesIndexedPath(image_index
);
350 const struct mach_header
* dyld_image_header_containing_address(const void* address
)
352 if ( dyld::gLogAPIs
)
353 dyld::log("%s(%p)\n", __func__
, address
);
354 #if SUPPORT_ACCELERATE_TABLES
355 const mach_header
* mh
;
357 if ( dyld::addressInCache(address
, &mh
, &path
) )
360 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
362 return image
->machHeader();
367 void _dyld_register_func_for_add_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
369 if ( dyld::gLogAPIs
)
370 dyld::log("%s(%p)\n", __func__
, (void *)func
);
371 dyld::registerAddCallback(func
);
374 void _dyld_register_func_for_remove_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
376 if ( dyld::gLogAPIs
)
377 dyld::log("%s(%p)\n", __func__
, (void *)func
);
378 dyld::registerRemoveCallback(func
);
383 // called by crt before main() by programs linked with 10.4 or earlier crt1.o
384 static void _dyld_make_delayed_module_initializer_calls()
386 if ( dyld::gLogAPIs
)
387 dyld::log("%s()\n", __func__
);
389 #if SUPPORT_OLD_CRT_INITIALIZATION
390 if ( dyld::gRunInitializersOldWay
)
391 dyld::initializeMainExecutable();
397 #if DEPRECATED_APIS_SUPPORTED
400 // _dyld_call_module_initializers_for_dylib() is the dyld side of
401 // __initialize_Cplusplus() which is in dylib1.o.
402 // It is intended to only be called inside -init rouintes.
403 // -init routines are called before module initializers (what C++
404 // initializers use). Calling __initialize_Cplusplus() in a -init
405 // routine causes the module initializers for an image to be called
406 // which then allows C++ to be used inside a -init routine
408 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
)
410 if ( dyld::gLogAPIs
)
411 dyld::log("__initialize_Cplusplus()\n");
413 // for now, do nothing...
417 void _dyld_lookup_and_bind_fully(const char* symbolName
, void** address
, NSModule
* module)
419 if ( dyld::gLogAPIs
)
420 dyld::log("%s(\"%s\", %p, %p)\n", __func__
, symbolName
, address
, module);
422 const ImageLoader::Symbol
* sym
;
423 dyld::clearErrorMessage();
424 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, (const ImageLoader
**)&image
) ) {
426 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
427 if ( address
!= NULL
)
428 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
430 *module = ImageLoaderToNSModule(image
);
432 catch (const char* msg
) {
433 dyldAPIhalt(__func__
, msg
);
437 // on failure to find symbol return NULLs
438 if ( address
!= NULL
)
445 // Note: This cannot have public name because dyld is built with a static copy of libc.a
446 // which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
447 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module)
449 if ( dyld::gLogAPIs
)
450 dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName
, address
, module);
451 const ImageLoader
* image
;
452 const ImageLoader::Symbol
* sym
;
453 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
454 if ( address
!= NULL
)
455 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
457 *module = ImageLoaderToNSModule(image
);
460 // on failure to find symbol return NULLs
461 if ( address
!= NULL
)
468 void _dyld_lookup_and_bind_with_hint(const char* symbolName
, const char* library_name_hint
, void** address
, NSModule
* module)
470 if ( dyld::gLogAPIs
)
471 dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__
, symbolName
, library_name_hint
, address
, module);
472 const ImageLoader
* image
;
473 const ImageLoader::Symbol
* sym
;
474 // Look for library whose path contains the hint. If that fails search everywhere
475 if ( dyld::flatFindExportedSymbolWithHint(symbolName
, library_name_hint
, &sym
, &image
)
476 || dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
477 if ( address
!= NULL
)
478 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
480 *module = ImageLoaderToNSModule(image
);
483 // on failure to find symbol return NULLs
484 if ( address
!= NULL
)
492 NSSymbol
NSLookupAndBindSymbol(const char *symbolName
)
494 if ( dyld::gLogAPIs
)
495 dyld::log("%s(\"%s\")\n", __func__
, symbolName
);
496 const ImageLoader
* image
;
497 const ImageLoader::Symbol
* sym
;
498 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
499 return SymbolToNSSymbol(sym
);
501 // return NULL on failure
505 NSSymbol
NSLookupAndBindSymbolWithHint(const char* symbolName
, const char* libraryNameHint
)
507 if ( dyld::gLogAPIs
)
508 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
509 const ImageLoader
* image
;
510 const ImageLoader::Symbol
* sym
;
511 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
513 // hint failed, do slow search of all images
514 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
517 return SymbolToNSSymbol(sym
);
519 // return NULL on failure and log
520 if ( dyld::gLogAPIs
)
521 dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__
, symbolName
, libraryNameHint
);
528 static __attribute__((noinline
))
529 const struct mach_header
* addImage(void* callerAddress
, const char* path
, bool search
, bool dontLoad
, bool matchInstallName
, bool abortOnError
)
531 ImageLoader
* image
= NULL
;
532 std::vector
<const char*> rpathsFromCallerImage
;
534 dyld::clearErrorMessage();
535 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
536 // like dlopen, use rpath from caller image and from main executable
537 if ( callerImage
!= NULL
)
538 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
539 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
540 if ( callerImage
!= dyld::mainExecutable() ) {
541 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
543 dyld::LoadContext context
;
544 context
.useSearchPaths
= search
;
545 context
.useFallbackPaths
= search
;
546 context
.useLdLibraryPath
= false;
547 context
.implicitRPath
= false;
548 context
.matchByInstallName
= matchInstallName
;
549 context
.dontLoad
= dontLoad
;
550 context
.mustBeBundle
= false;
551 context
.mustBeDylib
= true;
552 context
.canBePIE
= false;
553 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
554 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
557 image
= load(path
, context
, cacheIndex
);
558 if ( image
!= NULL
) {
559 if ( context
.matchByInstallName
)
560 image
->setMatchInstallPath(true);
561 dyld::link(image
, false, false, callersRPaths
, cacheIndex
);
562 dyld::runInitializers(image
);
563 // images added with NSAddImage() can never be unloaded
564 image
->setNeverUnload();
567 catch (const char* msg
) {
568 dyld::garbageCollectImages();
570 char pathMsg
[strlen(msg
)+strlen(path
)+4];
571 strcpy(pathMsg
, msg
);
572 strcat(pathMsg
, " ");
573 strcat(pathMsg
, path
);
574 dyldAPIhalt("NSAddImage", pathMsg
);
576 // not halting, so set error state for NSLinkEditError to find
577 setLastError(NSLinkEditOtherError
, 0, path
, msg
);
578 free((void*)msg
); // our free() will do nothing if msg is a string literal
581 // free rpaths (getRPaths() malloc'ed each string)
582 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
583 const char* str
= *it
;
589 return image
->machHeader();
593 const struct mach_header
* NSAddImage(const char* path
, uint32_t options
)
595 if ( dyld::gLogAPIs
)
596 dyld::log("%s(\"%s\", 0x%08X)\n", __func__
, path
, options
);
597 const bool dontLoad
= ( (options
& NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
) != 0 );
598 const bool search
= ( (options
& NSADDIMAGE_OPTION_WITH_SEARCHING
) != 0 );
599 const bool matchInstallName
= ( (options
& NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME
) != 0 );
600 const bool abortOnError
= ( (options
& (NSADDIMAGE_OPTION_RETURN_ON_ERROR
|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
)) == 0 );
601 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
602 return addImage(callerAddress
, path
, search
, dontLoad
, matchInstallName
, abortOnError
);
605 bool NSAddLibrary(const char* path
)
607 if ( dyld::gLogAPIs
)
608 dyld::log("%s(\"%s\")\n", __func__
, path
);
609 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
610 return (addImage(callerAddress
, path
, false, false, false, false) != NULL
);
613 bool NSAddLibraryWithSearching(const char* path
)
615 if ( dyld::gLogAPIs
)
616 dyld::log("%s(\"%s\")\n", __func__
, path
);
617 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
618 return (addImage(callerAddress
, path
, true, false, false, false) != NULL
);
623 //#define NSADDIMAGE_OPTION_NONE 0x0
624 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
625 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
627 bool NSIsSymbolNameDefinedInImage(const struct mach_header
* mh
, const char* symbolName
)
629 if ( dyld::gLogAPIs
)
630 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)mh
, symbolName
);
631 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
632 if ( image
!= NULL
) {
633 if ( image
->findExportedSymbol(symbolName
, true, NULL
) != NULL
)
640 NSSymbol
NSLookupSymbolInImage(const struct mach_header
* mh
, const char* symbolName
, uint32_t options
)
642 if ( dyld::gLogAPIs
)
643 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, mh
, symbolName
, options
);
644 const ImageLoader::Symbol
* symbol
= NULL
;
645 dyld::clearErrorMessage();
646 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
647 if ( image
!= NULL
) {
649 if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY
) {
650 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
652 else if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
) {
653 image
->bindAllLazyPointers(dyld::gLinkContext
, false);
656 catch (const char* msg
) {
657 if ( (options
& NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
) == 0 ) {
658 dyldAPIhalt(__func__
, msg
);
661 symbol
= image
->findExportedSymbol(symbolName
, true, NULL
);
663 if ( dyld::gLogAPIs
&& (symbol
== NULL
) )
664 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__
, mh
, symbolName
, options
);
665 return SymbolToNSSymbol(symbol
);
669 // Note: This cannot have public name because dyld is built with a static copy of libc.a
670 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
671 static bool client_NSIsSymbolNameDefined(const char* symbolName
)
673 if ( dyld::gLogAPIs
)
674 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName
);
675 const ImageLoader
* image
;
676 const ImageLoader::Symbol
* sym
;
677 return dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
680 bool NSIsSymbolNameDefinedWithHint(const char* symbolName
, const char* libraryNameHint
)
682 if ( dyld::gLogAPIs
)
683 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
684 const ImageLoader
* image
;
685 const ImageLoader::Symbol
* sym
;
686 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
688 // hint failed, do slow search of all images
689 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
691 if ( !found
&& dyld::gLogAPIs
)
692 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__
, symbolName
, libraryNameHint
);
696 const char* NSNameOfSymbol(NSSymbol symbol
)
698 if ( dyld::gLogAPIs
)
699 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
700 const char* result
= NULL
;
701 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
703 result
= image
->getExportedSymbolName(NSSymbolToSymbol(symbol
));
707 void* NSAddressOfSymbol(NSSymbol symbol
)
709 if ( dyld::gLogAPIs
)
710 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
711 if ( symbol
== NULL
)
714 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
716 result
= (void*)image
->getExportedSymbolAddress(NSSymbolToSymbol(symbol
), dyld::gLinkContext
);
720 NSModule
NSModuleForSymbol(NSSymbol symbol
)
722 if ( dyld::gLogAPIs
)
723 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
724 NSModule result
= NULL
;
725 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
727 result
= ImageLoaderToNSModule(image
);
734 bool _dyld_all_twolevel_modules_prebound(void)
736 if ( dyld::gLogAPIs
)
737 dyld::log("%s()\n", __func__
);
741 bool _dyld_bind_fully_image_containing_address(const void* address
)
743 if ( dyld::gLogAPIs
)
744 dyld::log("%s(%p)\n", __func__
, address
);
745 dyld::clearErrorMessage();
746 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
747 if ( image
!= NULL
) {
749 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
752 catch (const char* msg
) {
753 dyldAPIhalt(__func__
, msg
);
759 bool _dyld_image_containing_address(const void* address
)
761 if ( dyld::gLogAPIs
)
762 dyld::log("%s(%p)\n", __func__
, address
);
763 ImageLoader
*imageLoader
= dyld::findImageContainingAddress(address
);
764 return (NULL
!= imageLoader
);
767 static NSObjectFileImage
createObjectImageFile(ImageLoader
* image
, const void* address
= NULL
, size_t len
=0)
769 NSObjectFileImage result
= new __NSObjectFileImage();
770 result
->image
= image
;
771 result
->imageBaseAddress
= address
;
772 result
->imageLength
= len
;
773 sObjectFileImages
.push_back(result
);
777 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* pathName
, NSObjectFileImage
*objectFileImage
)
779 if ( dyld::gLogAPIs
)
780 dyld::log("%s(\"%s\", ...)\n", __func__
, pathName
);
782 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
783 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
785 dyld::LoadContext context
;
786 context
.useSearchPaths
= false;
787 context
.useFallbackPaths
= false;
788 context
.useLdLibraryPath
= false;
789 context
.implicitRPath
= false;
790 context
.matchByInstallName
= false;
791 context
.dontLoad
= false;
792 context
.mustBeBundle
= true;
793 context
.mustBeDylib
= false;
794 context
.canBePIE
= false;
795 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
796 context
.rpath
= NULL
; // support not yet implemented
799 ImageLoader
* image
= dyld::load(pathName
, context
, cacheIndex
);
800 // Note: We DO NOT link the image! NSLinkModule will do that
801 if ( image
!= NULL
) {
802 if ( !image
->isBundle() ) {
803 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
804 return NSObjectFileImageInappropriateFile
;
806 *objectFileImage
= createObjectImageFile(image
);
807 return NSObjectFileImageSuccess
;
810 catch (const char* msg
) {
811 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
812 dyld::garbageCollectImages();
814 return NSObjectFileImageInappropriateFile
;
816 return NSObjectFileImageFailure
;
820 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* address
, size_t size
, NSObjectFileImage
*objectFileImage
)
822 if ( dyld::gLogAPIs
)
823 dyld::log("%s(%p, %lu, %p)\n", __func__
, address
, size
, objectFileImage
);
826 ImageLoader
* image
= dyld::loadFromMemory((const uint8_t*)address
, size
, NULL
);
827 if ( ! image
->isBundle() ) {
828 // this API can only be used with bundles...
829 dyld::garbageCollectImages();
830 return NSObjectFileImageInappropriateFile
;
832 // Note: We DO NOT link the image! NSLinkModule will do that
833 if ( image
!= NULL
) {
834 *objectFileImage
= createObjectImageFile(image
, address
, size
);
835 return NSObjectFileImageSuccess
;
838 catch (const char* msg
) {
840 dyld::garbageCollectImages();
841 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
843 return NSObjectFileImageFailure
;
846 static bool validOFI(NSObjectFileImage objectFileImage
)
848 const size_t ofiCount
= sObjectFileImages
.size();
849 for (size_t i
=0; i
< ofiCount
; ++i
) {
850 if ( sObjectFileImages
[i
] == objectFileImage
)
856 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage
)
858 if ( dyld::gLogAPIs
)
859 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
861 if ( validOFI(objectFileImage
) ) {
862 // a failure during NSLinkModule will delete the image
863 if ( objectFileImage
->image
!= NULL
) {
864 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
865 // and we should delete it
866 bool linkedImage
= dyld::validImage(objectFileImage
->image
);
867 if ( ! linkedImage
) {
868 ImageLoader::deleteImage(objectFileImage
->image
);
869 objectFileImage
->image
= NULL
;
873 // remove from list of ofi's
874 for (std::vector
<NSObjectFileImage
>::iterator it
=sObjectFileImages
.begin(); it
!= sObjectFileImages
.end(); it
++) {
875 if ( *it
== objectFileImage
) {
876 sObjectFileImages
.erase(it
);
881 // if object was created from a memory, release that memory
882 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
883 if ( objectFileImage
->imageBaseAddress
!= NULL
) {
885 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 6) ) {
886 size_t sz
= (*dyld::gLibSystemHelpers
->malloc_size
)(objectFileImage
->imageBaseAddress
);
888 (*dyld::gLibSystemHelpers
->free
)((void*)(objectFileImage
->imageBaseAddress
));
893 vm_deallocate(mach_task_self(), (vm_address_t
)objectFileImage
->imageBaseAddress
, objectFileImage
->imageLength
);
897 delete objectFileImage
;
904 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
906 if ( dyld::gLogAPIs
)
907 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
908 return objectFileImage
->image
->getExportedSymbolCount();
911 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
913 if ( dyld::gLogAPIs
)
914 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
915 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedExportedSymbol(ordinal
);
916 return objectFileImage
->image
->getExportedSymbolName(sym
);
919 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
921 if ( dyld::gLogAPIs
)
922 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
923 return objectFileImage
->image
->getImportedSymbolCount();
926 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
,
927 bool* tentative_definition
)
929 if ( dyld::gLogAPIs
)
930 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
931 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedImportedSymbol(ordinal
);
932 if ( tentative_definition
!= NULL
) {
933 ImageLoader::ReferenceFlags flags
= objectFileImage
->image
->getImportedSymbolInfo(sym
);
934 if ( (flags
& ImageLoader::kTentativeDefinition
) != 0 )
935 *tentative_definition
= true;
937 *tentative_definition
= false;
939 return objectFileImage
->image
->getImportedSymbolName(sym
);
942 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage
,
943 const char* segmentName
, const char* sectionName
, unsigned long* size
)
945 if ( dyld::gLogAPIs
)
946 dyld::log("%s(%p,%s, %s)\n", __func__
, objectFileImage
, segmentName
, sectionName
);
950 if ( objectFileImage
->image
->getSectionContent(segmentName
, sectionName
, &start
, &length
) ) {
960 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage
, const char* symbolName
)
962 if ( dyld::gLogAPIs
)
963 dyld::log("%s(%p,%s)\n", __func__
, objectFileImage
, symbolName
);
964 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->findExportedSymbol(symbolName
, true, NULL
);
965 return ( sym
!= NULL
);
970 NSModule
NSLinkModule(NSObjectFileImage objectFileImage
, const char* moduleName
, uint32_t options
)
972 if ( dyld::gLogAPIs
)
973 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, objectFileImage
, moduleName
, options
);
975 dyld::clearErrorMessage();
977 if ( (options
& NSLINKMODULE_OPTION_CAN_UNLOAD
) != 0 )
978 objectFileImage
->image
->setCanUnload();
980 // NSLinkModule allows a bundle to be link multpile times
981 // each link causes the bundle to be copied to a new address
982 if ( objectFileImage
->image
->isLinked() ) {
983 // already linked, so clone a new one and link it
984 objectFileImage
->image
= dyld::cloneImage(objectFileImage
->image
);
987 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
988 if ( objectFileImage
->image
->getPath() == NULL
) {
989 objectFileImage
->image
->setPath(moduleName
);
990 // <rdar://problem/8812589> dyld has NULL paths in image info array
991 dyld_image_info info
;
992 info
.imageLoadAddress
= objectFileImage
->image
->machHeader();
993 info
.imageFilePath
= moduleName
;
994 info
.imageFileModDate
= 0;
995 addImagesToAllImages(1, &info
);
998 // support private bundles
999 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1000 objectFileImage
->image
->setHideExports();
1002 // set up linking options
1003 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1005 // load libraries, rebase, bind, to make this image usable
1006 dyld::link(objectFileImage
->image
, forceLazysBound
, false, ImageLoader::RPathChain(NULL
,NULL
), UINT32_MAX
);
1008 // bump reference count to keep this bundle from being garbage collected
1009 objectFileImage
->image
->incrementDlopenReferenceCount();
1011 // run initializers unless magic flag says not to
1012 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1013 dyld::runInitializers(objectFileImage
->image
);
1015 return ImageLoaderToNSModule(objectFileImage
->image
);
1017 catch (const char* msg
) {
1018 dyld::garbageCollectImages();
1019 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1020 dyldAPIhalt(__func__
, msg
);
1021 // not halting, so set error state for NSLinkEditError to find
1022 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1023 // dyld::link() deleted the image so lose our reference
1024 objectFileImage
->image
= NULL
;
1031 #if OLD_LIBSYSTEM_SUPPORT
1032 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1033 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
)
1035 if ( dyld::gLogAPIs
)
1036 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr
, moduleName
, options
); // note name/args translation
1037 ImageLoader
* image
= NULL
;
1038 dyld::clearErrorMessage();
1040 const char* imageName
= moduleName
;
1041 image
= dyld::loadFromMemory((const uint8_t*)object_addr
, object_size
, imageName
);
1043 if ( image
!= NULL
) {
1044 // support private bundles
1045 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1046 image
->setHideExports();
1048 // set up linking options
1049 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1051 // load libraries, rebase, bind, to make this image usable
1052 dyld::link(image
, forceLazysBound
, false, ImageLoader::RPathChain(NULL
,NULL
), UINT32_MAX
);
1054 // run initializers unless magic flag says not to
1055 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1056 dyld::runInitializers(image
);
1059 catch (const char* msg
) {
1060 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1061 dyldAPIhalt("NSLinkModule", msg
);
1062 // not halting, so set error state for NSLinkEditError to find
1063 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1064 // if image was created for this bundle, destroy it
1065 if ( image
!= NULL
) {
1066 dyld::removeImage(image
);
1067 ImageLoader::deleteImage(image
);
1072 return ImageLoaderToNSModule(image
);
1076 NSSymbol
NSLookupSymbolInModule(NSModule
module, const char* symbolName
)
1078 if ( dyld::gLogAPIs
)
1079 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)module, symbolName
);
1080 ImageLoader
* image
= NSModuleToImageLoader(module);
1081 if ( image
== NULL
)
1083 return SymbolToNSSymbol(image
->findExportedSymbol(symbolName
, false, NULL
));
1086 const char* NSNameOfModule(NSModule
module)
1088 if ( dyld::gLogAPIs
)
1089 dyld::log("%s(%p)\n", __func__
, module);
1090 ImageLoader
* image
= NSModuleToImageLoader(module);
1091 if ( image
== NULL
)
1093 return image
->getPath();
1096 const char* NSLibraryNameForModule(NSModule
module)
1098 if ( dyld::gLogAPIs
)
1099 dyld::log("%s(%p)\n", __func__
, module);
1100 ImageLoader
* image
= NSModuleToImageLoader(module);
1101 if ( image
== NULL
)
1103 return image
->getPath();
1106 bool NSUnLinkModule(NSModule
module, uint32_t options
)
1108 if ( dyld::gLogAPIs
)
1109 dyld::log("%s(%p, 0x%08X)\n", __func__
, module, options
);
1110 if ( module == NULL
)
1112 ImageLoader
* image
= NSModuleToImageLoader(module);
1113 if ( image
== NULL
)
1115 dyld::runImageStaticTerminators(image
);
1116 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 13) ) {
1117 __cxa_range_t ranges
[image
->segmentCount()];
1119 for (unsigned int j
=0; j
< image
->segmentCount(); ++j
) {
1120 if ( !image
->segExecutable(j
) )
1122 ranges
[rangeCount
].addr
= (const void*)image
->segActualLoadAddress(j
);
1123 ranges
[rangeCount
].length
= image
->segSize(j
);
1126 (*dyld::gLibSystemHelpers
->cxa_finalize_ranges
)(ranges
, rangeCount
);
1128 dyld::removeImage(image
);
1130 if ( (options
& NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
) != 0 )
1131 image
->setLeaveMapped();
1133 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1135 // Only delete image if there is no ofi referencing it
1136 // That means the ofi was destroyed after linking, so no one is left to delete this image
1137 const size_t ofiCount
= sObjectFileImages
.size();
1139 for (size_t i
=0; i
< ofiCount
; ++i
) {
1140 NSObjectFileImage ofi
= sObjectFileImages
[i
];
1141 if ( ofi
->image
== image
)
1145 ImageLoader::deleteImage(image
);
1150 // internal name and parameters do not match public name and parameters...
1151 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
)
1153 if ( dyld::gLogAPIs
)
1154 dyld::log("NSLinkEditErrorHandlers()\n");
1156 dyld::registerUndefinedHandler((dyld::UndefinedHandler
)undefined
);
1157 // no support for multiple or linkedit handlers
1163 void NSLinkEditError(NSLinkEditErrors
* c
, int* errorNumber
, const char** fileName
, const char** errorString
)
1166 *c
= sLastErrorFileCode
;
1167 *errorNumber
= sLastErrorNo
;
1168 *fileName
= sLastErrorFilePath
;
1169 *errorString
= dyld::getErrorMessage();
1174 static void _dyld_register_binding_handler(void * (*bindingHandler
)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions
)
1176 if ( dyld::gLogAPIs
)
1177 dyld::log("%s()\n", __func__
);
1178 dyld::gLinkContext
.bindingHandler
= bindingHandler
;
1179 dyld::gLinkContext
.bindingOptions
= bindingOptions
;
1182 #endif //DEPRECATED_APIS_SUPPORTED
1185 // Call by fork() in libSystem after the kernel trap is done on the child side
1186 void _dyld_fork_child()
1188 if ( dyld::gLogAPIs
)
1189 dyld::log("%s()\n", __func__
);
1190 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1191 // in libSystem for the child of a fork. But dyld is built with a static copy
1192 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1194 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1195 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1197 extern mach_port_t mach_task_self_
;
1198 mach_task_self_
= task_self_trap();
1200 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1201 // page is not copied on fork. <rdar://problem/6797342>
1202 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1203 dyld::gProcessInfo
->coreSymbolicationShmPage
= NULL
;
1204 // for safety, make sure child starts with clean systemOrderFlag
1205 dyld::gProcessInfo
->systemOrderFlag
= 0;
1209 #if DEPRECATED_APIS_SUPPORTED
1210 // returns true if prebinding was used in main executable
1211 bool _dyld_launched_prebound()
1213 if ( dyld::gLogAPIs
)
1214 dyld::log("%s()\n", __func__
);
1216 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1217 return dyld::mainExecutablePrebound();
1222 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1223 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1224 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1225 // flag on the image for this module. If the module was found and it was
1226 // private then everything worked and TRUE is returned else FALSE is returned.
1228 static bool NSMakePrivateModulePublic(NSModule
module)
1230 ImageLoader
* image
= NSModuleToImageLoader(module);
1231 if ( image
!= NULL
) {
1232 if ( image
->hasHiddenExports() ) {
1233 image
->setHideExports(false);
1240 #endif // DEPRECATED_APIS_SUPPORTED
1242 int _dyld_func_lookup(const char* name
, void** address
)
1244 for (const dyld_func
* p
= dyld_funcs
; p
->name
!= NULL
; ++p
) {
1245 if ( strcmp(p
->name
, name
) == 0 ) {
1246 if( p
->implementation
== unimplemented
)
1247 dyld::log("unimplemented dyld function: %s\n", p
->name
);
1248 *address
= p
->implementation
;
1257 static void registerThreadHelpers(const dyld::LibSystemHelpers
* helpers
)
1259 dyld::gLibSystemHelpers
= helpers
;
1261 #if !SUPPORT_ZERO_COST_EXCEPTIONS
1262 if ( helpers
->version
>= 5 ) {
1263 // create key use by dyld exception handling
1265 int result
= helpers
->pthread_key_create(&key
, NULL
);
1267 __Unwind_SjLj_SetThreadKey(key
);
1273 static void dlerrorClear()
1275 if ( dyld::gLibSystemHelpers
!= NULL
) {
1276 // <rdar://problem/10595338> dlerror buffer leak
1277 // dlerrorClear() should not force allocation, but zero it if already allocated
1278 if ( dyld::gLibSystemHelpers
->version
>= 10 ) {
1279 if ( ! (*dyld::gLibSystemHelpers
->hasPerThreadBufferFor_dlerror
)() )
1283 // first char of buffer is flag whether string (starting at second char) is valid
1284 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1290 static void dlerrorSet(const char* msg
)
1292 if ( dyld::gLibSystemHelpers
!= NULL
) {
1293 // first char of buffer is flag whether string (starting at second char) is valid
1294 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(strlen(msg
)+2);
1296 strcpy(&buffer
[1], msg
);
1301 bool dlopen_preflight(const char* path
)
1303 if ( dyld::gLogAPIs
)
1304 dyld::log("%s(%s)\n", __func__
, path
);
1308 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
1310 const bool leafName
= (strchr(path
, '/') == NULL
);
1311 const bool absolutePath
= (path
[0] == '/');
1312 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1313 char canonicalPath
[PATH_MAX
];
1314 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1316 // make path canonical if it contains a // or ./
1317 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1318 const char* lastSlash
= strrchr(path
, '/');
1319 char dirPath
[PATH_MAX
];
1320 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1321 dirPath
[lastSlash
-path
] = '\0';
1322 if ( realpath(dirPath
, canonicalPath
) ) {
1323 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1324 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1325 // if all fit in buffer, use new canonical path
1326 path
= canonicalPath
;
1333 #if SUPPORT_ACCELERATE_TABLES
1334 if ( dyld::isPathInCache(path
) )
1338 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1339 // if requested path is to something in the dyld shared cache, always succeed
1340 if ( dyld::inSharedCache(path
) )
1343 bool result
= false;
1344 std::vector
<const char*> rpathsFromCallerImage
;
1346 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1347 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1348 // for dlopen, use rpath from caller image and from main executable
1349 if ( callerImage
!= NULL
)
1350 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1351 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1352 if ( callerImage
!= dyld::mainExecutable() ) {
1353 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1356 ImageLoader
* image
= NULL
;
1357 dyld::LoadContext context
;
1358 context
.useSearchPaths
= true;
1359 context
.useFallbackPaths
= leafName
; // a partial path implies don't use fallback paths
1360 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1361 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1362 context
.matchByInstallName
= true;
1363 context
.dontLoad
= false;
1364 context
.mustBeBundle
= false;
1365 context
.mustBeDylib
= false;
1366 context
.canBePIE
= true;
1367 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1368 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1370 unsigned cacheIndex
;
1371 image
= load(path
, context
, cacheIndex
);
1372 if ( image
!= NULL
) {
1373 dyld::preflight(image
, callersRPaths
, cacheIndex
); // image object deleted by dyld::preflight()
1377 catch (const char* msg
) {
1378 const char* str
= dyld::mkstringf("dlopen_preflight(%s): %s", path
, msg
);
1381 free((void*)msg
); // our free() will do nothing if msg is a string literal
1383 // free rpaths (getRPaths() malloc'ed each string)
1384 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1385 const char* str
= *it
;
1388 CRSetCrashLogMessage(NULL
);
1392 #if SUPPORT_ACCELERATE_TABLES
1393 bool static callerIsNonOSApp(void* callerAddress
, const char** shortName
)
1396 const mach_header
* unusedMh
;
1397 const char* unusedPath
;
1398 unsigned unusedIndex
;
1399 // any address in shared cache is not from app
1400 if ( dyld::addressInCache(callerAddress
, &unusedMh
, &unusedPath
, &unusedIndex
) )
1403 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1404 if ( callerImage
== NULL
)
1407 *shortName
= callerImage
->getShortName();
1408 return ( strncmp(callerImage
->getPath(), "/var/containers/", 16) == 0 );
1412 void* dlopen(const char* path
, int mode
)
1414 if ( dyld::gLogAPIs
)
1415 dyld::log("%s(%s, 0x%08X)\n", __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1417 #if SUPPORT_ACCELERATE_TABLES
1418 if ( dyld::gLogAppAPIs
) {
1419 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1420 const char* shortName
;
1421 if ( callerIsNonOSApp(callerAddress
, &shortName
) ) {
1422 dyld::log("%s: %s(%s, 0x%08X)\n", shortName
, __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1429 // passing NULL for path means return magic object
1430 if ( path
== NULL
) {
1431 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1432 if ( (mode
& RTLD_FIRST
) != 0 )
1433 return RTLD_MAIN_ONLY
;
1435 return RTLD_DEFAULT
;
1438 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1439 bool lockHeld
= false;
1440 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 4) ) {
1441 dyld::gLibSystemHelpers
->acquireGlobalDyldLock();
1442 CRSetCrashLogMessage("dyld: in dlopen()");
1446 void* result
= NULL
;
1447 const bool leafName
= (strchr(path
, '/') == NULL
);
1448 const bool absolutePath
= (path
[0] == '/');
1449 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1450 char canonicalPath
[PATH_MAX
];
1451 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1453 // make path canonical if it contains a // or ./
1454 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1455 const char* lastSlash
= strrchr(path
, '/');
1456 char dirPath
[PATH_MAX
];
1457 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1458 dirPath
[lastSlash
-path
] = '\0';
1459 if ( realpath(dirPath
, canonicalPath
) ) {
1460 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1461 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1462 // if all fit in buffer, use new canonical path
1463 path
= canonicalPath
;
1470 #if SUPPORT_ACCELERATE_TABLES
1471 if ( dyld::dlopenFromCache(path
, mode
, &result
) ) {
1472 // Note: dlopenFromCache() releases the lock
1473 if ( dyld::gLogAPIs
)
1474 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1479 ImageLoader
* image
= NULL
;
1480 std::vector
<const char*> rpathsFromCallerImage
;
1481 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1483 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1484 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1485 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1486 // for dlopen, use rpath from caller image and from main executable
1487 if ( callerImage
!= NULL
)
1488 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1489 if ( callerImage
!= dyld::mainExecutable() )
1490 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1493 dyld::LoadContext context
;
1494 context
.useSearchPaths
= true;
1495 context
.useFallbackPaths
= leafName
; // a partial path means no fallback paths
1496 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1497 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1498 context
.matchByInstallName
= true;
1499 context
.dontLoad
= ( (mode
& RTLD_NOLOAD
) != 0 );
1500 context
.mustBeBundle
= false;
1501 context
.mustBeDylib
= false;
1502 context
.canBePIE
= true;
1503 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1504 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1506 unsigned cacheIndex
;
1507 image
= load(path
, context
, cacheIndex
);
1508 #if SUPPORT_ACCELERATE_TABLES
1509 if ( (image
!= NULL
) && (cacheIndex
!= UINT32_MAX
) ) {
1510 // found in cache, but under a different path
1511 const char* betterPath
= dyld::getPathFromIndex(cacheIndex
);
1512 if ( (betterPath
!= NULL
) && dyld::dlopenFromCache(betterPath
, mode
, &result
) ) {
1513 // Note: dlopenFromCache() releases the lock
1514 if ( dyld::gLogAPIs
)
1515 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1520 if ( image
!= NULL
) {
1521 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1522 // this image is not garbage collected
1523 image
->incrementDlopenReferenceCount();
1524 // link in all dependents
1525 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1526 bool alreadyLinked
= image
->isLinked();
1527 bool forceLazysBound
= ( (mode
& RTLD_NOW
) != 0 );
1528 dyld::link(image
, forceLazysBound
, false, callersRPaths
, cacheIndex
);
1529 if ( ! alreadyLinked
) {
1530 // only hide exports if image is not already in use
1531 if ( (mode
& RTLD_LOCAL
) != 0 )
1532 image
->setHideExports(true);
1536 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1537 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1538 // The subtle differences are:
1539 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1540 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1541 if ( (mode
& RTLD_NODELETE
) != 0 )
1542 image
->setLeaveMapped();
1544 // release global dyld lock early, this enables initializers to do threaded operations
1546 CRSetCrashLogMessage(NULL
);
1547 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1551 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1552 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1553 // called from within an initializer because it can cause initializers to run
1554 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1555 // to run, then don't use RTLD_NOLOAD.
1556 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1558 dyld::runInitializers(image
);
1561 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1562 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1563 if ( (mode
& RTLD_FIRST
) != 0 )
1564 result
= (void*)(((uintptr_t)image
)|1);
1569 catch (const char* msg
) {
1570 if ( image
!= NULL
) {
1571 // load() succeeded but, link() failed
1572 // back down reference count and do GC
1573 image
->decrementDlopenReferenceCount();
1574 if ( image
->dlopenCount() == 0 )
1575 dyld::garbageCollectImages();
1577 const char* str
= dyld::mkstringf("dlopen(%s, %d): %s", path
, mode
, msg
);
1578 if ( dyld::gLogAPIs
)
1579 dyld::log(" %s() failed, error: '%s'\n", __func__
, str
);
1582 free((void*)msg
); // our free() will do nothing if msg is a string literal
1585 // free rpaths (getRPaths() malloc'ed each string)
1586 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1587 const char* str
= *it
;
1591 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1592 if ( (mode
& RTLD_NOLOAD
) && (result
== NULL
) ) {
1593 dlerrorSet("image not already loaded");
1597 CRSetCrashLogMessage(NULL
);
1598 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1600 if ( dyld::gLogAPIs
&& (result
!= NULL
) )
1601 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1607 int dlclose(void* handle
)
1609 if ( dyld::gLogAPIs
)
1610 dyld::log("%s(%p)\n", __func__
, handle
);
1612 // silently accept magic handles for main executable
1613 if ( handle
== RTLD_MAIN_ONLY
)
1615 if ( handle
== RTLD_DEFAULT
)
1618 ImageLoader
* image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1619 if ( dyld::validImage(image
) ) {
1621 // decrement use count
1622 if ( image
->decrementDlopenReferenceCount() ) {
1623 dlerrorSet("dlclose() called too many times");
1626 // remove image if reference count went to zero
1627 if ( image
->dlopenCount() == 0 )
1628 dyld::garbageCollectImages();
1632 dlerrorSet("invalid handle passed to dlclose()");
1639 int dladdr(const void* address
, Dl_info
* info
)
1641 if ( dyld::gLogAPIs
)
1642 dyld::log("%s(%p, %p)\n", __func__
, address
, info
);
1644 CRSetCrashLogMessage("dyld: in dladdr()");
1645 #if SUPPORT_ACCELERATE_TABLES
1646 if ( dyld::dladdrFromCache(address
, info
) ) {
1647 CRSetCrashLogMessage(NULL
);
1648 return 1; // success
1652 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1653 if ( image
!= NULL
) {
1654 info
->dli_fname
= image
->getRealPath();
1655 info
->dli_fbase
= (void*)image
->machHeader();
1656 if ( address
== info
->dli_fbase
) {
1657 // special case lookup of header
1658 info
->dli_sname
= "__dso_handle";
1659 info
->dli_saddr
= info
->dli_fbase
;
1660 CRSetCrashLogMessage(NULL
);
1661 return 1; // success
1663 // find closest symbol in the image
1664 info
->dli_sname
= image
->findClosestSymbol(address
, (const void**)&info
->dli_saddr
);
1665 // never return the mach_header symbol
1666 if ( info
->dli_saddr
== info
->dli_fbase
) {
1667 info
->dli_sname
= NULL
;
1668 info
->dli_saddr
= NULL
;
1669 CRSetCrashLogMessage(NULL
);
1670 return 1; // success
1672 if ( info
->dli_sname
!= NULL
) {
1673 if ( info
->dli_sname
[0] == '_' )
1674 info
->dli_sname
= info
->dli_sname
+1; // strip off leading underscore
1675 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1676 CRSetCrashLogMessage(NULL
);
1677 return 1; // success
1679 info
->dli_sname
= NULL
;
1680 info
->dli_saddr
= NULL
;
1681 CRSetCrashLogMessage(NULL
);
1682 return 1; // success
1684 CRSetCrashLogMessage(NULL
);
1685 return 0; // failure
1691 if ( dyld::gLogAPIs
)
1692 dyld::log("%s()\n", __func__
);
1694 if ( dyld::gLibSystemHelpers
!= NULL
) {
1695 // if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
1696 if ( dyld::gLibSystemHelpers
->version
>= 10 ) {
1697 if ( ! (*dyld::gLibSystemHelpers
->hasPerThreadBufferFor_dlerror
)() )
1701 // first char of buffer is flag whether string (starting at second char) is valid
1702 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1703 if ( buffer
[0] != '\0' ) { // if valid buffer
1704 buffer
[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1705 return &buffer
[1]; // return message
1711 void* dlsym(void* handle
, const char* symbolName
)
1713 if ( dyld::gLogAPIs
)
1714 dyld::log("%s(%p, %s)\n", __func__
, handle
, symbolName
);
1716 #if SUPPORT_ACCELERATE_TABLES
1717 if ( dyld::gLogAppAPIs
) {
1718 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1719 const char* shortName
;
1720 if ( callerIsNonOSApp(callerAddress
, &shortName
) ) {
1721 dyld::log("%s: %s(%p, %s)\n", shortName
, __func__
, handle
, symbolName
);
1726 CRSetCrashLogMessage("dyld: in dlsym()");
1729 const ImageLoader
* image
;
1730 const ImageLoader::Symbol
* sym
;
1733 // dlsym() assumes symbolName passed in is same as in C source code
1734 // dyld assumes all symbol names have an underscore prefix
1735 char underscoredName
[strlen(symbolName
)+2];
1736 underscoredName
[0] = '_';
1737 strcpy(&underscoredName
[1], symbolName
);
1739 // magic "search all" handle
1740 if ( handle
== RTLD_DEFAULT
) {
1741 if ( dyld::flatFindExportedSymbol(underscoredName
, &sym
, &image
) ) {
1742 CRSetCrashLogMessage(NULL
);
1743 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, NULL
, false, underscoredName
);
1744 if ( dyld::gLogAPIs
)
1745 dyld::log(" %s(RTLD_DEFAULT, %s) ==> %p\n", __func__
, symbolName
, result
);
1748 const char* str
= dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName
);
1751 CRSetCrashLogMessage(NULL
);
1752 if ( dyld::gLogAPIs
)
1753 dyld::log(" %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__
, symbolName
);
1757 // magic "search only main executable" handle
1758 else if ( handle
== RTLD_MAIN_ONLY
) {
1759 image
= dyld::mainExecutable();
1760 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1761 if ( sym
!= NULL
) {
1762 CRSetCrashLogMessage(NULL
);
1763 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, NULL
, false, underscoredName
);
1764 if ( dyld::gLogAPIs
)
1765 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__
, symbolName
, result
);
1768 const char* str
= dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName
);
1771 CRSetCrashLogMessage(NULL
);
1772 if ( dyld::gLogAPIs
)
1773 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__
, symbolName
);
1777 // magic "search what I would see" handle
1778 else if ( handle
== RTLD_NEXT
) {
1779 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1780 #if SUPPORT_ACCELERATE_TABLES
1781 const mach_header
* mh
;
1784 if ( dyld::addressInCache(callerAddress
, &mh
, &path
, &index
) ) {
1785 // if dylib in cache is calling dlsym(RTLD_NEXT,xxx) handle search differently
1786 result
= dyld::dlsymFromCache(RTLD_NEXT
, underscoredName
, index
);
1787 if ( dyld::gLogAPIs
)
1788 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1792 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1793 sym
= callerImage
->findExportedSymbolInDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // don't search image, but do search what it links against
1794 if ( sym
!= NULL
) {
1795 CRSetCrashLogMessage(NULL
);
1796 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1797 if ( dyld::gLogAPIs
)
1798 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1801 const char* str
= dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName
);
1804 CRSetCrashLogMessage(NULL
);
1805 if ( dyld::gLogAPIs
)
1806 dyld::log(" %s(RTLD_NEXT, %s) ==> NULL\n", __func__
, symbolName
);
1809 // magic "search me, then what I would see" handle
1810 else if ( handle
== RTLD_SELF
) {
1811 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1812 #if SUPPORT_ACCELERATE_TABLES
1813 const mach_header
* mh
;
1816 if ( dyld::addressInCache(callerAddress
, &mh
, &path
, &index
) ) {
1817 // if dylib in cache is calling dlsym(RTLD_SELF,xxx) handle search differently
1818 result
= dyld::dlsymFromCache(RTLD_SELF
, underscoredName
, index
);
1819 if ( dyld::gLogAPIs
)
1820 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1824 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1825 sym
= callerImage
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1826 if ( sym
!= NULL
) {
1827 CRSetCrashLogMessage(NULL
);
1828 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1829 if ( dyld::gLogAPIs
)
1830 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1833 const char* str
= dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName
);
1836 CRSetCrashLogMessage(NULL
);
1837 if ( dyld::gLogAPIs
)
1838 dyld::log(" %s(RTLD_SELF, %s) ==> NULL\n", __func__
, symbolName
);
1841 #if SUPPORT_ACCELERATE_TABLES
1842 // check for mega dylib handle
1843 else if ( dyld::isCacheHandle(handle
) ) {
1844 result
= dyld::dlsymFromCache(handle
, underscoredName
, 0);
1845 if ( dyld::gLogAPIs
)
1846 dyld::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
1851 image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1852 if ( dyld::validImage(image
) ) {
1853 if ( (((uintptr_t)handle
) & 1) != 0 )
1854 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1856 sym
= image
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1858 if ( sym
!= NULL
) {
1859 CRSetCrashLogMessage(NULL
);
1860 ImageLoader
* callerImage
= NULL
;
1861 if ( sDynamicInterposing
) {
1862 // only take time to look up caller, if dynamic interposing in use
1863 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1864 callerImage
= dyld::findImageContainingAddress(callerAddress
);
1866 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1867 if ( dyld::gLogAPIs
)
1868 dyld::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
1871 const char* str
= dyld::mkstringf("dlsym(%p, %s): symbol not found", handle
, symbolName
);
1876 dlerrorSet("invalid handle passed to dlsym()");
1878 CRSetCrashLogMessage(NULL
);
1879 if ( dyld::gLogAPIs
)
1880 dyld::log(" %s(%p, %s) ==> NULL\n", __func__
, handle
, symbolName
);
1893 const struct dyld_all_image_infos
* _dyld_get_all_image_infos()
1895 return dyld::gProcessInfo
;
1899 #if SUPPORT_ZERO_COST_EXCEPTIONS
1900 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
)
1902 //if ( dyld::gLogAPIs )
1903 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
1905 #if SUPPORT_ACCELERATE_TABLES
1906 if ( dyld::findUnwindSections(addr
, info
) )
1909 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
1910 if ( image
!= NULL
) {
1911 image
->getUnwindInfo(info
);
1919 const char* dyld_image_path_containing_address(const void* address
)
1921 if ( dyld::gLogAPIs
)
1922 dyld::log("%s(%p)\n", __func__
, address
);
1924 #if SUPPORT_ACCELERATE_TABLES
1925 const mach_header
* mh
;
1927 if ( dyld::addressInCache(address
, &mh
, &path
) )
1931 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1932 if ( image
!= NULL
)
1933 return image
->getRealPath();
1939 bool dyld_shared_cache_some_image_overridden()
1941 return dyld::gSharedCacheOverridden
;
1945 void dyld_dynamic_interpose(const struct mach_header
* mh
, const struct dyld_interpose_tuple array
[], size_t count
)
1949 if ( array
== NULL
)
1953 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
1954 if ( image
== NULL
)
1957 // make pass at bound references in this image and update them
1958 dyld::gLinkContext
.dynamicInterposeArray
= array
;
1959 dyld::gLinkContext
.dynamicInterposeCount
= count
;
1960 image
->dynamicInterpose(dyld::gLinkContext
);
1961 dyld::gLinkContext
.dynamicInterposeArray
= NULL
;
1962 dyld::gLinkContext
.dynamicInterposeCount
= 0;
1964 // leave interposing info so any future (lazy) binding will get it too
1965 image
->addDynamicInterposingTuples(array
, count
);
1967 sDynamicInterposing
= true;
1971 bool _dyld_is_memory_immutable(const void* addr
, size_t length
)
1973 if ( dyld::gLogAPIs
)
1974 dyld::log("%s(%p, %ld)\n", __func__
, addr
, length
);
1976 uintptr_t checkStart
= (uintptr_t)addr
;
1977 uintptr_t checkEnd
= checkStart
+ length
;
1979 // quick check to see if in r/o region of shared cache. If so return true.
1980 const DyldSharedCache
* cache
= (DyldSharedCache
*)dyld::imMemorySharedCacheHeader();
1981 if ( cache
!= nullptr ) {
1982 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)((char*)cache
+ cache
->header
.mappingOffset
);
1983 uintptr_t roStart
= (uintptr_t)cache
;
1984 uintptr_t roEnd
= roStart
+ (uintptr_t)mappings
[0].size
;
1985 if ( (roStart
< checkStart
) && (checkEnd
< roEnd
) )
1989 // Otherwise find if addr is in a dyld loaded image
1990 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
1991 if ( image
!= NULL
) {
1992 // <rdar://problem/24091154> already checked for r/o portion of cache
1993 if ( image
->inSharedCache() )
1995 if ( !image
->neverUnload() )
1997 for (unsigned i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
1998 if ( (image
->segActualLoadAddress(i
) < checkStart
) && (checkEnd
< image
->segActualEndAddress(i
)) ) {
1999 return !image
->segWriteable(i
);
2008 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped
,
2009 _dyld_objc_notify_init init
,
2010 _dyld_objc_notify_unmapped unmapped
)
2012 dyld::registerObjCNotifiers(mapped
, init
, unmapped
);
2016 bool _dyld_get_shared_cache_uuid(uuid_t uuid
)
2018 return dyld::sharedCacheUUID(uuid
);
2021 const void* _dyld_get_shared_cache_range(size_t* length
)
2023 const DyldSharedCache
* cache
= (DyldSharedCache
*)dyld::imMemorySharedCacheHeader();
2024 if ( cache
!= nullptr ) {
2025 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)((char*)cache
+ cache
->header
.mappingOffset
);
2026 *length
= (size_t)((mappings
[2].address
+ mappings
[2].size
) - mappings
[0].address
);