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
) {
648 const char* symbolToFind
= symbolName
;
650 if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY
) {
651 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
653 else if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
) {
654 image
->bindAllLazyPointers(dyld::gLinkContext
, false);
657 catch (const char* msg
) {
658 if ( (options
& NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
) == 0 ) {
659 dyldAPIhalt(__func__
, msg
);
662 symbol
= image
->findExportedSymbol(symbolToFind
, true, NULL
);
664 if ( dyld::gLogAPIs
&& (symbol
== NULL
) )
665 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__
, mh
, symbolName
, options
);
666 return SymbolToNSSymbol(symbol
);
670 // Note: This cannot have public name because dyld is built with a static copy of libc.a
671 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
672 static bool client_NSIsSymbolNameDefined(const char* symbolName
)
674 if ( dyld::gLogAPIs
)
675 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName
);
676 const ImageLoader
* image
;
677 const ImageLoader::Symbol
* sym
;
678 return dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
681 bool NSIsSymbolNameDefinedWithHint(const char* symbolName
, const char* libraryNameHint
)
683 if ( dyld::gLogAPIs
)
684 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
685 const ImageLoader
* image
;
686 const ImageLoader::Symbol
* sym
;
687 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
689 // hint failed, do slow search of all images
690 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
692 if ( !found
&& dyld::gLogAPIs
)
693 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__
, symbolName
, libraryNameHint
);
697 const char* NSNameOfSymbol(NSSymbol symbol
)
699 if ( dyld::gLogAPIs
)
700 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
701 const char* result
= NULL
;
702 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
704 result
= image
->getExportedSymbolName(NSSymbolToSymbol(symbol
));
708 void* NSAddressOfSymbol(NSSymbol symbol
)
710 if ( dyld::gLogAPIs
)
711 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
712 if ( symbol
== NULL
)
715 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
717 result
= (void*)image
->getExportedSymbolAddress(NSSymbolToSymbol(symbol
), dyld::gLinkContext
);
721 NSModule
NSModuleForSymbol(NSSymbol symbol
)
723 if ( dyld::gLogAPIs
)
724 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
725 NSModule result
= NULL
;
726 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
728 result
= ImageLoaderToNSModule(image
);
735 bool _dyld_all_twolevel_modules_prebound(void)
737 if ( dyld::gLogAPIs
)
738 dyld::log("%s()\n", __func__
);
742 bool _dyld_bind_fully_image_containing_address(const void* address
)
744 if ( dyld::gLogAPIs
)
745 dyld::log("%s(%p)\n", __func__
, address
);
746 dyld::clearErrorMessage();
747 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
748 if ( image
!= NULL
) {
750 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
753 catch (const char* msg
) {
754 dyldAPIhalt(__func__
, msg
);
760 bool _dyld_image_containing_address(const void* address
)
762 if ( dyld::gLogAPIs
)
763 dyld::log("%s(%p)\n", __func__
, address
);
764 ImageLoader
*imageLoader
= dyld::findImageContainingAddress(address
);
765 return (NULL
!= imageLoader
);
768 static NSObjectFileImage
createObjectImageFile(ImageLoader
* image
, const void* address
= NULL
, size_t len
=0)
770 NSObjectFileImage result
= new __NSObjectFileImage();
771 result
->image
= image
;
772 result
->imageBaseAddress
= address
;
773 result
->imageLength
= len
;
774 sObjectFileImages
.push_back(result
);
778 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* pathName
, NSObjectFileImage
*objectFileImage
)
780 if ( dyld::gLogAPIs
)
781 dyld::log("%s(\"%s\", ...)\n", __func__
, pathName
);
783 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
784 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
786 dyld::LoadContext context
;
787 context
.useSearchPaths
= false;
788 context
.useFallbackPaths
= false;
789 context
.useLdLibraryPath
= false;
790 context
.implicitRPath
= false;
791 context
.matchByInstallName
= false;
792 context
.dontLoad
= false;
793 context
.mustBeBundle
= true;
794 context
.mustBeDylib
= false;
795 context
.canBePIE
= false;
796 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
797 context
.rpath
= NULL
; // support not yet implemented
800 ImageLoader
* image
= dyld::load(pathName
, context
, cacheIndex
);
801 // Note: We DO NOT link the image! NSLinkModule will do that
802 if ( image
!= NULL
) {
803 if ( !image
->isBundle() ) {
804 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
805 return NSObjectFileImageInappropriateFile
;
807 *objectFileImage
= createObjectImageFile(image
);
808 return NSObjectFileImageSuccess
;
811 catch (const char* msg
) {
812 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
813 dyld::garbageCollectImages();
815 return NSObjectFileImageInappropriateFile
;
817 return NSObjectFileImageFailure
;
821 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* address
, size_t size
, NSObjectFileImage
*objectFileImage
)
823 if ( dyld::gLogAPIs
)
824 dyld::log("%s(%p, %lu, %p)\n", __func__
, address
, size
, objectFileImage
);
827 ImageLoader
* image
= dyld::loadFromMemory((const uint8_t*)address
, size
, NULL
);
828 if ( ! image
->isBundle() ) {
829 // this API can only be used with bundles...
830 dyld::garbageCollectImages();
831 return NSObjectFileImageInappropriateFile
;
833 // Note: We DO NOT link the image! NSLinkModule will do that
834 if ( image
!= NULL
) {
835 *objectFileImage
= createObjectImageFile(image
, address
, size
);
836 return NSObjectFileImageSuccess
;
839 catch (const char* msg
) {
841 dyld::garbageCollectImages();
842 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
844 return NSObjectFileImageFailure
;
847 static bool validOFI(NSObjectFileImage objectFileImage
)
849 const size_t ofiCount
= sObjectFileImages
.size();
850 for (size_t i
=0; i
< ofiCount
; ++i
) {
851 if ( sObjectFileImages
[i
] == objectFileImage
)
857 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage
)
859 if ( dyld::gLogAPIs
)
860 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
862 if ( validOFI(objectFileImage
) ) {
863 // a failure during NSLinkModule will delete the image
864 if ( objectFileImage
->image
!= NULL
) {
865 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
866 // and we should delete it
867 bool linkedImage
= dyld::validImage(objectFileImage
->image
);
868 if ( ! linkedImage
) {
869 ImageLoader::deleteImage(objectFileImage
->image
);
870 objectFileImage
->image
= NULL
;
874 // remove from list of ofi's
875 for (std::vector
<NSObjectFileImage
>::iterator it
=sObjectFileImages
.begin(); it
!= sObjectFileImages
.end(); it
++) {
876 if ( *it
== objectFileImage
) {
877 sObjectFileImages
.erase(it
);
882 // if object was created from a memory, release that memory
883 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
884 if ( objectFileImage
->imageBaseAddress
!= NULL
) {
886 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 6) ) {
887 size_t sz
= (*dyld::gLibSystemHelpers
->malloc_size
)(objectFileImage
->imageBaseAddress
);
889 (*dyld::gLibSystemHelpers
->free
)((void*)(objectFileImage
->imageBaseAddress
));
894 vm_deallocate(mach_task_self(), (vm_address_t
)objectFileImage
->imageBaseAddress
, objectFileImage
->imageLength
);
898 delete objectFileImage
;
905 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
907 if ( dyld::gLogAPIs
)
908 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
909 return objectFileImage
->image
->getExportedSymbolCount();
912 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
914 if ( dyld::gLogAPIs
)
915 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
916 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedExportedSymbol(ordinal
);
917 return objectFileImage
->image
->getExportedSymbolName(sym
);
920 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
922 if ( dyld::gLogAPIs
)
923 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
924 return objectFileImage
->image
->getImportedSymbolCount();
927 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
,
928 bool* tentative_definition
)
930 if ( dyld::gLogAPIs
)
931 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
932 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedImportedSymbol(ordinal
);
933 if ( tentative_definition
!= NULL
) {
934 ImageLoader::ReferenceFlags flags
= objectFileImage
->image
->getImportedSymbolInfo(sym
);
935 if ( (flags
& ImageLoader::kTentativeDefinition
) != 0 )
936 *tentative_definition
= true;
938 *tentative_definition
= false;
940 return objectFileImage
->image
->getImportedSymbolName(sym
);
943 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage
,
944 const char* segmentName
, const char* sectionName
, unsigned long* size
)
946 if ( dyld::gLogAPIs
)
947 dyld::log("%s(%p,%s, %s)\n", __func__
, objectFileImage
, segmentName
, sectionName
);
951 if ( objectFileImage
->image
->getSectionContent(segmentName
, sectionName
, &start
, &length
) ) {
961 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage
, const char* symbolName
)
963 if ( dyld::gLogAPIs
)
964 dyld::log("%s(%p,%s)\n", __func__
, objectFileImage
, symbolName
);
965 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->findExportedSymbol(symbolName
, true, NULL
);
966 return ( sym
!= NULL
);
971 NSModule
NSLinkModule(NSObjectFileImage objectFileImage
, const char* moduleName
, uint32_t options
)
973 if ( dyld::gLogAPIs
)
974 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, objectFileImage
, moduleName
, options
);
976 dyld::clearErrorMessage();
978 if ( (options
& NSLINKMODULE_OPTION_CAN_UNLOAD
) != 0 )
979 objectFileImage
->image
->setCanUnload();
981 // NSLinkModule allows a bundle to be link multpile times
982 // each link causes the bundle to be copied to a new address
983 if ( objectFileImage
->image
->isLinked() ) {
984 // already linked, so clone a new one and link it
985 objectFileImage
->image
= dyld::cloneImage(objectFileImage
->image
);
988 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
989 if ( objectFileImage
->image
->getPath() == NULL
) {
990 objectFileImage
->image
->setPath(moduleName
);
991 // <rdar://problem/8812589> dyld has NULL paths in image info array
992 dyld_image_info info
;
993 info
.imageLoadAddress
= objectFileImage
->image
->machHeader();
994 info
.imageFilePath
= moduleName
;
995 info
.imageFileModDate
= 0;
996 addImagesToAllImages(1, &info
);
999 // support private bundles
1000 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1001 objectFileImage
->image
->setHideExports();
1003 // set up linking options
1004 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1006 // load libraries, rebase, bind, to make this image usable
1007 dyld::link(objectFileImage
->image
, forceLazysBound
, false, ImageLoader::RPathChain(NULL
,NULL
), UINT32_MAX
);
1009 // bump reference count to keep this bundle from being garbage collected
1010 objectFileImage
->image
->incrementDlopenReferenceCount();
1012 // run initializers unless magic flag says not to
1013 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1014 dyld::runInitializers(objectFileImage
->image
);
1016 return ImageLoaderToNSModule(objectFileImage
->image
);
1018 catch (const char* msg
) {
1019 dyld::garbageCollectImages();
1020 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1021 dyldAPIhalt(__func__
, msg
);
1022 // not halting, so set error state for NSLinkEditError to find
1023 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1024 // dyld::link() deleted the image so lose our reference
1025 objectFileImage
->image
= NULL
;
1032 #if OLD_LIBSYSTEM_SUPPORT
1033 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1034 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
)
1036 if ( dyld::gLogAPIs
)
1037 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr
, moduleName
, options
); // note name/args translation
1038 ImageLoader
* image
= NULL
;
1039 dyld::clearErrorMessage();
1041 const char* imageName
= moduleName
;
1042 image
= dyld::loadFromMemory((const uint8_t*)object_addr
, object_size
, imageName
);
1044 if ( image
!= NULL
) {
1045 // support private bundles
1046 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1047 image
->setHideExports();
1049 // set up linking options
1050 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1052 // load libraries, rebase, bind, to make this image usable
1053 dyld::link(image
, forceLazysBound
, false, ImageLoader::RPathChain(NULL
,NULL
), UINT32_MAX
);
1055 // run initializers unless magic flag says not to
1056 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1057 dyld::runInitializers(image
);
1060 catch (const char* msg
) {
1061 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1062 dyldAPIhalt("NSLinkModule", msg
);
1063 // not halting, so set error state for NSLinkEditError to find
1064 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1065 // if image was created for this bundle, destroy it
1066 if ( image
!= NULL
) {
1067 dyld::removeImage(image
);
1068 ImageLoader::deleteImage(image
);
1073 return ImageLoaderToNSModule(image
);
1077 NSSymbol
NSLookupSymbolInModule(NSModule
module, const char* symbolName
)
1079 if ( dyld::gLogAPIs
)
1080 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)module, symbolName
);
1081 ImageLoader
* image
= NSModuleToImageLoader(module);
1082 if ( image
== NULL
)
1084 return SymbolToNSSymbol(image
->findExportedSymbol(symbolName
, false, NULL
));
1087 const char* NSNameOfModule(NSModule
module)
1089 if ( dyld::gLogAPIs
)
1090 dyld::log("%s(%p)\n", __func__
, module);
1091 ImageLoader
* image
= NSModuleToImageLoader(module);
1092 if ( image
== NULL
)
1094 return image
->getPath();
1097 const char* NSLibraryNameForModule(NSModule
module)
1099 if ( dyld::gLogAPIs
)
1100 dyld::log("%s(%p)\n", __func__
, module);
1101 ImageLoader
* image
= NSModuleToImageLoader(module);
1102 if ( image
== NULL
)
1104 return image
->getPath();
1107 bool NSUnLinkModule(NSModule
module, uint32_t options
)
1109 if ( dyld::gLogAPIs
)
1110 dyld::log("%s(%p, 0x%08X)\n", __func__
, module, options
);
1111 if ( module == NULL
)
1113 ImageLoader
* image
= NSModuleToImageLoader(module);
1114 if ( image
== NULL
)
1116 dyld::runImageStaticTerminators(image
);
1117 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 13) ) {
1118 __cxa_range_t ranges
[image
->segmentCount()];
1120 for (unsigned int j
=0; j
< image
->segmentCount(); ++j
) {
1121 if ( !image
->segExecutable(j
) )
1123 ranges
[rangeCount
].addr
= (const void*)image
->segActualLoadAddress(j
);
1124 ranges
[rangeCount
].length
= image
->segSize(j
);
1127 (*dyld::gLibSystemHelpers
->cxa_finalize_ranges
)(ranges
, rangeCount
);
1129 dyld::removeImage(image
);
1131 if ( (options
& NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
) != 0 )
1132 image
->setLeaveMapped();
1134 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1136 // Only delete image if there is no ofi referencing it
1137 // That means the ofi was destroyed after linking, so no one is left to delete this image
1138 const size_t ofiCount
= sObjectFileImages
.size();
1140 for (size_t i
=0; i
< ofiCount
; ++i
) {
1141 NSObjectFileImage ofi
= sObjectFileImages
[i
];
1142 if ( ofi
->image
== image
)
1146 ImageLoader::deleteImage(image
);
1151 // internal name and parameters do not match public name and parameters...
1152 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
)
1154 if ( dyld::gLogAPIs
)
1155 dyld::log("NSLinkEditErrorHandlers()\n");
1157 dyld::registerUndefinedHandler((dyld::UndefinedHandler
)undefined
);
1158 // no support for multiple or linkedit handlers
1164 void NSLinkEditError(NSLinkEditErrors
* c
, int* errorNumber
, const char** fileName
, const char** errorString
)
1167 *c
= sLastErrorFileCode
;
1168 *errorNumber
= sLastErrorNo
;
1169 *fileName
= sLastErrorFilePath
;
1170 *errorString
= dyld::getErrorMessage();
1175 static void _dyld_register_binding_handler(void * (*bindingHandler
)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions
)
1177 if ( dyld::gLogAPIs
)
1178 dyld::log("%s()\n", __func__
);
1179 dyld::gLinkContext
.bindingHandler
= bindingHandler
;
1180 dyld::gLinkContext
.bindingOptions
= bindingOptions
;
1183 #endif //DEPRECATED_APIS_SUPPORTED
1186 // Call by fork() in libSystem after the kernel trap is done on the child side
1187 void _dyld_fork_child()
1189 if ( dyld::gLogAPIs
)
1190 dyld::log("%s()\n", __func__
);
1191 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1192 // in libSystem for the child of a fork. But dyld is built with a static copy
1193 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1195 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1196 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1198 extern mach_port_t mach_task_self_
;
1199 mach_task_self_
= task_self_trap();
1201 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1202 // page is not copied on fork. <rdar://problem/6797342>
1203 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1204 dyld::gProcessInfo
->coreSymbolicationShmPage
= NULL
;
1205 // for safety, make sure child starts with clean systemOrderFlag
1206 dyld::gProcessInfo
->systemOrderFlag
= 0;
1210 #if DEPRECATED_APIS_SUPPORTED
1211 // returns true if prebinding was used in main executable
1212 bool _dyld_launched_prebound()
1214 if ( dyld::gLogAPIs
)
1215 dyld::log("%s()\n", __func__
);
1217 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1218 return dyld::mainExecutablePrebound();
1223 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1224 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1225 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1226 // flag on the image for this module. If the module was found and it was
1227 // private then everything worked and TRUE is returned else FALSE is returned.
1229 static bool NSMakePrivateModulePublic(NSModule
module)
1231 ImageLoader
* image
= NSModuleToImageLoader(module);
1232 if ( image
!= NULL
) {
1233 if ( image
->hasHiddenExports() ) {
1234 image
->setHideExports(false);
1241 #endif // DEPRECATED_APIS_SUPPORTED
1243 int _dyld_func_lookup(const char* name
, void** address
)
1245 for (const dyld_func
* p
= dyld_funcs
; p
->name
!= NULL
; ++p
) {
1246 if ( strcmp(p
->name
, name
) == 0 ) {
1247 if( p
->implementation
== unimplemented
)
1248 dyld::log("unimplemented dyld function: %s\n", p
->name
);
1249 *address
= p
->implementation
;
1258 static void registerThreadHelpers(const dyld::LibSystemHelpers
* helpers
)
1260 dyld::gLibSystemHelpers
= helpers
;
1262 #if !SUPPORT_ZERO_COST_EXCEPTIONS
1263 if ( helpers
->version
>= 5 ) {
1264 // create key use by dyld exception handling
1266 int result
= helpers
->pthread_key_create(&key
, NULL
);
1268 __Unwind_SjLj_SetThreadKey(key
);
1274 static void dlerrorClear()
1276 if ( dyld::gLibSystemHelpers
!= NULL
) {
1277 // <rdar://problem/10595338> dlerror buffer leak
1278 // dlerrorClear() should not force allocation, but zero it if already allocated
1279 if ( dyld::gLibSystemHelpers
->version
>= 10 ) {
1280 if ( ! (*dyld::gLibSystemHelpers
->hasPerThreadBufferFor_dlerror
)() )
1284 // first char of buffer is flag whether string (starting at second char) is valid
1285 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1291 static void dlerrorSet(const char* msg
)
1293 if ( dyld::gLibSystemHelpers
!= NULL
) {
1294 // first char of buffer is flag whether string (starting at second char) is valid
1295 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(strlen(msg
)+2);
1297 strcpy(&buffer
[1], msg
);
1302 bool dlopen_preflight(const char* path
)
1304 if ( dyld::gLogAPIs
)
1305 dyld::log("%s(%s)\n", __func__
, path
);
1309 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
1311 const bool leafName
= (strchr(path
, '/') == NULL
);
1312 const bool absolutePath
= (path
[0] == '/');
1313 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1314 char canonicalPath
[PATH_MAX
];
1315 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1317 // make path canonical if it contains a // or ./
1318 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1319 const char* lastSlash
= strrchr(path
, '/');
1320 char dirPath
[PATH_MAX
];
1321 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1322 dirPath
[lastSlash
-path
] = '\0';
1323 if ( realpath(dirPath
, canonicalPath
) ) {
1324 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1325 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1326 // if all fit in buffer, use new canonical path
1327 path
= canonicalPath
;
1334 #if SUPPORT_ACCELERATE_TABLES
1335 if ( dyld::isPathInCache(path
) )
1339 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1340 // if requested path is to something in the dyld shared cache, always succeed
1341 if ( dyld::inSharedCache(path
) )
1344 bool result
= false;
1345 std::vector
<const char*> rpathsFromCallerImage
;
1347 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1348 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1349 // for dlopen, use rpath from caller image and from main executable
1350 if ( callerImage
!= NULL
)
1351 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1352 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1353 if ( callerImage
!= dyld::mainExecutable() ) {
1354 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1357 ImageLoader
* image
= NULL
;
1358 dyld::LoadContext context
;
1359 context
.useSearchPaths
= true;
1360 context
.useFallbackPaths
= leafName
; // a partial path implies don't use fallback paths
1361 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1362 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1363 context
.matchByInstallName
= true;
1364 context
.dontLoad
= false;
1365 context
.mustBeBundle
= false;
1366 context
.mustBeDylib
= false;
1367 context
.canBePIE
= true;
1368 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1369 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1371 unsigned cacheIndex
;
1372 image
= load(path
, context
, cacheIndex
);
1373 if ( image
!= NULL
) {
1374 dyld::preflight(image
, callersRPaths
, cacheIndex
); // image object deleted by dyld::preflight()
1378 catch (const char* msg
) {
1379 const char* str
= dyld::mkstringf("dlopen_preflight(%s): %s", path
, msg
);
1382 free((void*)msg
); // our free() will do nothing if msg is a string literal
1384 // free rpaths (getRPaths() malloc'ed each string)
1385 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1386 const char* str
= *it
;
1389 CRSetCrashLogMessage(NULL
);
1393 #if SUPPORT_ACCELERATE_TABLES
1394 bool static callerIsNonOSApp(void* callerAddress
, const char** shortName
)
1397 const mach_header
* unusedMh
;
1398 const char* unusedPath
;
1399 unsigned unusedIndex
;
1400 // any address in shared cache is not from app
1401 if ( dyld::addressInCache(callerAddress
, &unusedMh
, &unusedPath
, &unusedIndex
) )
1404 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1405 if ( callerImage
== NULL
)
1408 *shortName
= callerImage
->getShortName();
1409 return ( strncmp(callerImage
->getPath(), "/var/containers/", 16) == 0 );
1413 void* dlopen(const char* path
, int mode
)
1415 if ( dyld::gLogAPIs
)
1416 dyld::log("%s(%s, 0x%08X)\n", __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1418 #if SUPPORT_ACCELERATE_TABLES
1419 if ( dyld::gLogAppAPIs
) {
1420 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1421 const char* shortName
;
1422 if ( callerIsNonOSApp(callerAddress
, &shortName
) ) {
1423 dyld::log("%s: %s(%s, 0x%08X)\n", shortName
, __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1430 // passing NULL for path means return magic object
1431 if ( path
== NULL
) {
1432 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1433 if ( (mode
& RTLD_FIRST
) != 0 )
1434 return RTLD_MAIN_ONLY
;
1436 return RTLD_DEFAULT
;
1439 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1440 bool lockHeld
= false;
1441 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 4) ) {
1442 dyld::gLibSystemHelpers
->acquireGlobalDyldLock();
1443 CRSetCrashLogMessage("dyld: in dlopen()");
1447 void* result
= NULL
;
1448 const bool leafName
= (strchr(path
, '/') == NULL
);
1449 const bool absolutePath
= (path
[0] == '/');
1450 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1451 char canonicalPath
[PATH_MAX
];
1452 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1454 // make path canonical if it contains a // or ./
1455 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1456 const char* lastSlash
= strrchr(path
, '/');
1457 char dirPath
[PATH_MAX
];
1458 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1459 dirPath
[lastSlash
-path
] = '\0';
1460 if ( realpath(dirPath
, canonicalPath
) ) {
1461 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1462 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1463 // if all fit in buffer, use new canonical path
1464 path
= canonicalPath
;
1471 #if SUPPORT_ACCELERATE_TABLES
1472 if ( dyld::dlopenFromCache(path
, mode
, &result
) ) {
1473 // Note: dlopenFromCache() releases the lock
1474 if ( dyld::gLogAPIs
)
1475 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1480 ImageLoader
* image
= NULL
;
1481 std::vector
<const char*> rpathsFromCallerImage
;
1482 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1484 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1485 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1486 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1487 // for dlopen, use rpath from caller image and from main executable
1488 if ( callerImage
!= NULL
)
1489 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1490 if ( callerImage
!= dyld::mainExecutable() )
1491 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1494 dyld::LoadContext context
;
1495 context
.useSearchPaths
= true;
1496 context
.useFallbackPaths
= leafName
; // a partial path means no fallback paths
1497 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1498 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1499 context
.matchByInstallName
= true;
1500 context
.dontLoad
= ( (mode
& RTLD_NOLOAD
) != 0 );
1501 context
.mustBeBundle
= false;
1502 context
.mustBeDylib
= false;
1503 context
.canBePIE
= true;
1504 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1505 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1507 unsigned cacheIndex
;
1508 image
= load(path
, context
, cacheIndex
);
1509 #if SUPPORT_ACCELERATE_TABLES
1510 if ( (image
!= NULL
) && (cacheIndex
!= UINT32_MAX
) ) {
1511 // found in cache, but under a different path
1512 const char* betterPath
= dyld::getPathFromIndex(cacheIndex
);
1513 if ( (betterPath
!= NULL
) && dyld::dlopenFromCache(betterPath
, mode
, &result
) ) {
1514 // Note: dlopenFromCache() releases the lock
1515 if ( dyld::gLogAPIs
)
1516 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1521 if ( image
!= NULL
) {
1522 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1523 // this image is not garbage collected
1524 image
->incrementDlopenReferenceCount();
1525 // link in all dependents
1526 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1527 bool alreadyLinked
= image
->isLinked();
1528 bool forceLazysBound
= ( (mode
& RTLD_NOW
) != 0 );
1529 dyld::link(image
, forceLazysBound
, false, callersRPaths
, cacheIndex
);
1530 if ( ! alreadyLinked
) {
1531 // only hide exports if image is not already in use
1532 if ( (mode
& RTLD_LOCAL
) != 0 )
1533 image
->setHideExports(true);
1537 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1538 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1539 // The subtle differences are:
1540 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1541 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1542 if ( (mode
& RTLD_NODELETE
) != 0 )
1543 image
->setLeaveMapped();
1545 // release global dyld lock early, this enables initializers to do threaded operations
1547 CRSetCrashLogMessage(NULL
);
1548 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1552 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1553 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1554 // called from within an initializer because it can cause initializers to run
1555 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1556 // to run, then don't use RTLD_NOLOAD.
1557 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1559 dyld::runInitializers(image
);
1562 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1563 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1564 if ( (mode
& RTLD_FIRST
) != 0 )
1565 result
= (void*)(((uintptr_t)image
)|1);
1570 catch (const char* msg
) {
1571 if ( image
!= NULL
) {
1572 // load() succeeded but, link() failed
1573 // back down reference count and do GC
1574 image
->decrementDlopenReferenceCount();
1575 if ( image
->dlopenCount() == 0 )
1576 dyld::garbageCollectImages();
1578 const char* str
= dyld::mkstringf("dlopen(%s, %d): %s", path
, mode
, msg
);
1579 if ( dyld::gLogAPIs
)
1580 dyld::log(" %s() failed, error: '%s'\n", __func__
, str
);
1583 free((void*)msg
); // our free() will do nothing if msg is a string literal
1586 // free rpaths (getRPaths() malloc'ed each string)
1587 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1588 const char* str
= *it
;
1592 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1593 if ( (mode
& RTLD_NOLOAD
) && (result
== NULL
) ) {
1594 dlerrorSet("image not already loaded");
1598 CRSetCrashLogMessage(NULL
);
1599 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1601 if ( dyld::gLogAPIs
&& (result
!= NULL
) )
1602 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1608 int dlclose(void* handle
)
1610 if ( dyld::gLogAPIs
)
1611 dyld::log("%s(%p)\n", __func__
, handle
);
1613 // silently accept magic handles for main executable
1614 if ( handle
== RTLD_MAIN_ONLY
)
1616 if ( handle
== RTLD_DEFAULT
)
1619 ImageLoader
* image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1620 if ( dyld::validImage(image
) ) {
1622 // decrement use count
1623 if ( image
->decrementDlopenReferenceCount() ) {
1624 dlerrorSet("dlclose() called too many times");
1627 // remove image if reference count went to zero
1628 if ( image
->dlopenCount() == 0 )
1629 dyld::garbageCollectImages();
1633 dlerrorSet("invalid handle passed to dlclose()");
1640 int dladdr(const void* address
, Dl_info
* info
)
1642 if ( dyld::gLogAPIs
)
1643 dyld::log("%s(%p, %p)\n", __func__
, address
, info
);
1645 CRSetCrashLogMessage("dyld: in dladdr()");
1646 #if SUPPORT_ACCELERATE_TABLES
1647 if ( dyld::dladdrFromCache(address
, info
) ) {
1648 CRSetCrashLogMessage(NULL
);
1649 return 1; // success
1653 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1654 if ( image
!= NULL
) {
1655 info
->dli_fname
= image
->getRealPath();
1656 info
->dli_fbase
= (void*)image
->machHeader();
1657 if ( address
== info
->dli_fbase
) {
1658 // special case lookup of header
1659 info
->dli_sname
= "__dso_handle";
1660 info
->dli_saddr
= info
->dli_fbase
;
1661 CRSetCrashLogMessage(NULL
);
1662 return 1; // success
1664 // find closest symbol in the image
1665 info
->dli_sname
= image
->findClosestSymbol(address
, (const void**)&info
->dli_saddr
);
1666 // never return the mach_header symbol
1667 if ( info
->dli_saddr
== info
->dli_fbase
) {
1668 info
->dli_sname
= NULL
;
1669 info
->dli_saddr
= NULL
;
1670 CRSetCrashLogMessage(NULL
);
1671 return 1; // success
1673 if ( info
->dli_sname
!= NULL
) {
1674 if ( info
->dli_sname
[0] == '_' )
1675 info
->dli_sname
= info
->dli_sname
+1; // strip off leading underscore
1676 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1677 CRSetCrashLogMessage(NULL
);
1678 return 1; // success
1680 info
->dli_sname
= NULL
;
1681 info
->dli_saddr
= NULL
;
1682 CRSetCrashLogMessage(NULL
);
1683 return 1; // success
1685 CRSetCrashLogMessage(NULL
);
1686 return 0; // failure
1692 if ( dyld::gLogAPIs
)
1693 dyld::log("%s()\n", __func__
);
1695 if ( dyld::gLibSystemHelpers
!= NULL
) {
1696 // if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
1697 if ( dyld::gLibSystemHelpers
->version
>= 10 ) {
1698 if ( ! (*dyld::gLibSystemHelpers
->hasPerThreadBufferFor_dlerror
)() )
1702 // first char of buffer is flag whether string (starting at second char) is valid
1703 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1704 if ( buffer
[0] != '\0' ) { // if valid buffer
1705 buffer
[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1706 return &buffer
[1]; // return message
1712 void* dlsym(void* handle
, const char* symbolName
)
1714 if ( dyld::gLogAPIs
)
1715 dyld::log("%s(%p, %s)\n", __func__
, handle
, symbolName
);
1717 #if SUPPORT_ACCELERATE_TABLES
1718 if ( dyld::gLogAppAPIs
) {
1719 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1720 const char* shortName
;
1721 if ( callerIsNonOSApp(callerAddress
, &shortName
) ) {
1722 dyld::log("%s: %s(%p, %s)\n", shortName
, __func__
, handle
, symbolName
);
1727 CRSetCrashLogMessage("dyld: in dlsym()");
1730 const ImageLoader
* image
;
1731 const ImageLoader::Symbol
* sym
;
1734 // dlsym() assumes symbolName passed in is same as in C source code
1735 // dyld assumes all symbol names have an underscore prefix
1736 char underscoredName
[strlen(symbolName
)+2];
1737 underscoredName
[0] = '_';
1738 strcpy(&underscoredName
[1], symbolName
);
1740 // magic "search all" handle
1741 if ( handle
== RTLD_DEFAULT
) {
1742 if ( dyld::flatFindExportedSymbol(underscoredName
, &sym
, &image
) ) {
1743 CRSetCrashLogMessage(NULL
);
1744 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, NULL
, false, underscoredName
);
1745 if ( dyld::gLogAPIs
)
1746 dyld::log(" %s(RTLD_DEFAULT, %s) ==> %p\n", __func__
, symbolName
, result
);
1749 const char* str
= dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName
);
1752 CRSetCrashLogMessage(NULL
);
1753 if ( dyld::gLogAPIs
)
1754 dyld::log(" %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__
, symbolName
);
1758 // magic "search only main executable" handle
1759 else if ( handle
== RTLD_MAIN_ONLY
) {
1760 image
= dyld::mainExecutable();
1761 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1762 if ( sym
!= NULL
) {
1763 CRSetCrashLogMessage(NULL
);
1764 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, NULL
, false, underscoredName
);
1765 if ( dyld::gLogAPIs
)
1766 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__
, symbolName
, result
);
1769 const char* str
= dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName
);
1772 CRSetCrashLogMessage(NULL
);
1773 if ( dyld::gLogAPIs
)
1774 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__
, symbolName
);
1778 // magic "search what I would see" handle
1779 else if ( handle
== RTLD_NEXT
) {
1780 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1781 #if SUPPORT_ACCELERATE_TABLES
1782 const mach_header
* mh
;
1785 if ( dyld::addressInCache(callerAddress
, &mh
, &path
, &index
) ) {
1786 // if dylib in cache is calling dlsym(RTLD_NEXT,xxx) handle search differently
1787 result
= dyld::dlsymFromCache(RTLD_NEXT
, underscoredName
, index
);
1788 if ( dyld::gLogAPIs
)
1789 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1793 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1794 sym
= callerImage
->findExportedSymbolInDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // don't search image, but do search what it links against
1795 if ( sym
!= NULL
) {
1796 CRSetCrashLogMessage(NULL
);
1797 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1798 if ( dyld::gLogAPIs
)
1799 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1802 const char* str
= dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName
);
1805 CRSetCrashLogMessage(NULL
);
1806 if ( dyld::gLogAPIs
)
1807 dyld::log(" %s(RTLD_NEXT, %s) ==> NULL\n", __func__
, symbolName
);
1810 // magic "search me, then what I would see" handle
1811 else if ( handle
== RTLD_SELF
) {
1812 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1813 #if SUPPORT_ACCELERATE_TABLES
1814 const mach_header
* mh
;
1817 if ( dyld::addressInCache(callerAddress
, &mh
, &path
, &index
) ) {
1818 // if dylib in cache is calling dlsym(RTLD_SELF,xxx) handle search differently
1819 result
= dyld::dlsymFromCache(RTLD_SELF
, underscoredName
, index
);
1820 if ( dyld::gLogAPIs
)
1821 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1825 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1826 sym
= callerImage
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1827 if ( sym
!= NULL
) {
1828 CRSetCrashLogMessage(NULL
);
1829 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1830 if ( dyld::gLogAPIs
)
1831 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1834 const char* str
= dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName
);
1837 CRSetCrashLogMessage(NULL
);
1838 if ( dyld::gLogAPIs
)
1839 dyld::log(" %s(RTLD_SELF, %s) ==> NULL\n", __func__
, symbolName
);
1842 #if SUPPORT_ACCELERATE_TABLES
1843 // check for mega dylib handle
1844 else if ( dyld::isCacheHandle(handle
) ) {
1845 result
= dyld::dlsymFromCache(handle
, underscoredName
, 0);
1846 if ( dyld::gLogAPIs
)
1847 dyld::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
1852 image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1853 if ( dyld::validImage(image
) ) {
1854 if ( (((uintptr_t)handle
) & 1) != 0 )
1855 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1857 sym
= image
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1859 if ( sym
!= NULL
) {
1860 CRSetCrashLogMessage(NULL
);
1861 ImageLoader
* callerImage
= NULL
;
1862 if ( sDynamicInterposing
) {
1863 // only take time to look up caller, if dynamic interposing in use
1864 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1865 callerImage
= dyld::findImageContainingAddress(callerAddress
);
1867 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1868 if ( dyld::gLogAPIs
)
1869 dyld::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
1872 const char* str
= dyld::mkstringf("dlsym(%p, %s): symbol not found", handle
, symbolName
);
1877 dlerrorSet("invalid handle passed to dlsym()");
1879 CRSetCrashLogMessage(NULL
);
1880 if ( dyld::gLogAPIs
)
1881 dyld::log(" %s(%p, %s) ==> NULL\n", __func__
, handle
, symbolName
);
1894 const struct dyld_all_image_infos
* _dyld_get_all_image_infos()
1896 return dyld::gProcessInfo
;
1900 #if SUPPORT_ZERO_COST_EXCEPTIONS
1901 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
)
1903 //if ( dyld::gLogAPIs )
1904 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
1906 #if SUPPORT_ACCELERATE_TABLES
1907 if ( dyld::findUnwindSections(addr
, info
) )
1910 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
1911 if ( image
!= NULL
) {
1912 image
->getUnwindInfo(info
);
1920 const char* dyld_image_path_containing_address(const void* address
)
1922 if ( dyld::gLogAPIs
)
1923 dyld::log("%s(%p)\n", __func__
, address
);
1925 #if SUPPORT_ACCELERATE_TABLES
1926 const mach_header
* mh
;
1928 if ( dyld::addressInCache(address
, &mh
, &path
) )
1932 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1933 if ( image
!= NULL
)
1934 return image
->getRealPath();
1940 bool dyld_shared_cache_some_image_overridden()
1942 return dyld::gSharedCacheOverridden
;
1946 void dyld_dynamic_interpose(const struct mach_header
* mh
, const struct dyld_interpose_tuple array
[], size_t count
)
1950 if ( array
== NULL
)
1954 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
1955 if ( image
== NULL
)
1958 // make pass at bound references in this image and update them
1959 dyld::gLinkContext
.dynamicInterposeArray
= array
;
1960 dyld::gLinkContext
.dynamicInterposeCount
= count
;
1961 image
->dynamicInterpose(dyld::gLinkContext
);
1962 dyld::gLinkContext
.dynamicInterposeArray
= NULL
;
1963 dyld::gLinkContext
.dynamicInterposeCount
= 0;
1965 // leave interposing info so any future (lazy) binding will get it too
1966 image
->addDynamicInterposingTuples(array
, count
);
1968 sDynamicInterposing
= true;
1972 bool _dyld_is_memory_immutable(const void* addr
, size_t length
)
1974 if ( dyld::gLogAPIs
)
1975 dyld::log("%s(%p, %ld)\n", __func__
, addr
, length
);
1977 uintptr_t checkStart
= (uintptr_t)addr
;
1978 uintptr_t checkEnd
= checkStart
+ length
;
1980 // quick check to see if in r/o region of shared cache. If so return true.
1981 const DyldSharedCache
* cache
= (DyldSharedCache
*)dyld::imMemorySharedCacheHeader();
1982 if ( cache
!= nullptr ) {
1983 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)((char*)cache
+ cache
->header
.mappingOffset
);
1984 uintptr_t roStart
= (uintptr_t)cache
;
1985 uintptr_t roEnd
= roStart
+ (uintptr_t)mappings
[0].size
;
1986 if ( (roStart
< checkStart
) && (checkEnd
< roEnd
) )
1990 // Otherwise find if addr is in a dyld loaded image
1991 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
1992 if ( image
!= NULL
) {
1993 // <rdar://problem/24091154> already checked for r/o portion of cache
1994 if ( image
->inSharedCache() )
1996 if ( !image
->neverUnload() )
1998 for (unsigned i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
1999 if ( (image
->segActualLoadAddress(i
) < checkStart
) && (checkEnd
< image
->segActualEndAddress(i
)) ) {
2000 return !image
->segWriteable(i
);
2009 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped
,
2010 _dyld_objc_notify_init init
,
2011 _dyld_objc_notify_unmapped unmapped
)
2013 dyld::registerObjCNotifiers(mapped
, init
, unmapped
);
2017 bool _dyld_get_shared_cache_uuid(uuid_t uuid
)
2019 return dyld::sharedCacheUUID(uuid
);
2022 const void* _dyld_get_shared_cache_range(size_t* length
)
2024 const DyldSharedCache
* cache
= (DyldSharedCache
*)dyld::imMemorySharedCacheHeader();
2025 if ( cache
!= nullptr ) {
2026 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)((char*)cache
+ cache
->header
.mappingOffset
);
2027 *length
= (size_t)((mappings
[2].address
+ mappings
[2].size
) - mappings
[0].address
);