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"
55 #include "dyldLibSystemInterface.h"
57 #undef _POSIX_C_SOURCE
60 // from dyldExceptions.c
61 extern "C" void __Unwind_SjLj_SetThreadKey(pthread_key_t key
);
64 extern void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
66 // deprecated APIs are still availble on Mac OS X, but not on iPhone OS
67 #if __IPHONE_OS_VERSION_MIN_REQUIRED
68 #define DEPRECATED_APIS_SUPPORTED 0
70 #define DEPRECATED_APIS_SUPPORTED 1
74 #if DEPRECATED_APIS_SUPPORTED
75 static char sLastErrorFilePath
[1024];
76 static NSLinkEditErrors sLastErrorFileCode
;
77 static int sLastErrorNo
;
80 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
81 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
82 // This conditional keeps support for old libSystem's which needed some help implementing the API's
83 #define OLD_LIBSYSTEM_SUPPORT (__ppc__ || __i386__)
86 // The following functions have no prototype in any header. They are special cases
87 // where _dyld_func_lookup() is used directly.
88 static void _dyld_make_delayed_module_initializer_calls();
89 static void registerThreadHelpers(const dyld::LibSystemHelpers
*);
90 #if DEPRECATED_APIS_SUPPORTED
91 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
);
92 #if OLD_LIBSYSTEM_SUPPORT
93 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
);
95 static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions
);
96 static bool NSMakePrivateModulePublic(NSModule module
);
97 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
);
99 // The following functions are dyld API's, but since dyld links with a static copy of libc.a
100 // the public name cannot be used.
101 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module
);
102 static bool client_NSIsSymbolNameDefined(const char* symbolName
);
103 #endif // DEPRECATED_APIS_SUPPORTED
105 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
);
108 static void unimplemented()
110 dyld::halt("unimplemented dyld function\n");
115 void* implementation
;
118 static struct dyld_func dyld_funcs
[] = {
119 {"__dyld_register_func_for_add_image", (void*)_dyld_register_func_for_add_image
},
120 {"__dyld_register_func_for_remove_image", (void*)_dyld_register_func_for_remove_image
},
121 {"__dyld_dladdr", (void*)dladdr
},
122 {"__dyld_dlclose", (void*)dlclose
},
123 {"__dyld_dlerror", (void*)dlerror
},
124 {"__dyld_dlopen", (void*)dlopen
},
125 {"__dyld_dlsym", (void*)dlsym
},
126 {"__dyld_dlopen_preflight", (void*)dlopen_preflight
},
127 {"__dyld_image_count", (void*)_dyld_image_count
},
128 {"__dyld_get_image_header", (void*)_dyld_get_image_header
},
129 {"__dyld_get_image_vmaddr_slide", (void*)_dyld_get_image_vmaddr_slide
},
130 {"__dyld_get_image_name", (void*)_dyld_get_image_name
},
131 {"__dyld_get_image_slide", (void*)_dyld_get_image_slide
},
132 {"__dyld__NSGetExecutablePath", (void*)_NSGetExecutablePath
},
135 {"__dyld_dyld_register_image_state_change_handler", (void*)dyld_register_image_state_change_handler
},
136 {"__dyld_register_thread_helpers", (void*)registerThreadHelpers
},
137 {"__dyld_fork_child", (void*)_dyld_fork_child
},
138 {"__dyld_moninit", (void*)_dyld_moninit
},
139 {"__dyld_make_delayed_module_initializer_calls", (void*)_dyld_make_delayed_module_initializer_calls
},
140 {"__dyld_get_all_image_infos", (void*)_dyld_get_all_image_infos
},
142 {"__dyld_find_unwind_sections", (void*)client_dyld_find_unwind_sections
},
144 #if __i386__ || __x86_64__ || __arm__
145 {"__dyld_fast_stub_entry", (void*)dyld::fastBindLazySymbol
},
147 {"__dyld_image_path_containing_address", (void*)dyld_image_path_containing_address
},
148 #if __IPHONE_OS_VERSION_MIN_REQUIRED
149 {"__dyld_shared_cache_some_image_overridden", (void*)dyld_shared_cache_some_image_overridden
},
153 #if DEPRECATED_APIS_SUPPORTED
154 {"__dyld_get_image_header_containing_address", (void*)_dyld_get_image_header_containing_address
},
155 {"__dyld_lookup_and_bind", (void*)client_dyld_lookup_and_bind
},
156 {"__dyld_lookup_and_bind_with_hint", (void*)_dyld_lookup_and_bind_with_hint
},
157 {"__dyld_lookup_and_bind_fully", (void*)_dyld_lookup_and_bind_fully
},
158 {"__dyld_install_handlers", (void*)_dyld_install_handlers
},
159 {"__dyld_link_edit_error", (void*)NSLinkEditError
},
160 {"__dyld_unlink_module", (void*)NSUnLinkModule
},
161 {"__dyld_bind_objc_module", (void*)_dyld_bind_objc_module
},
162 {"__dyld_bind_fully_image_containing_address", (void*)_dyld_bind_fully_image_containing_address
},
163 {"__dyld_image_containing_address", (void*)_dyld_image_containing_address
},
164 {"__dyld_register_binding_handler", (void*)_dyld_register_binding_handler
},
165 {"__dyld_NSNameOfSymbol", (void*)NSNameOfSymbol
},
166 {"__dyld_NSAddressOfSymbol", (void*)NSAddressOfSymbol
},
167 {"__dyld_NSModuleForSymbol", (void*)NSModuleForSymbol
},
168 {"__dyld_NSLookupAndBindSymbol", (void*)NSLookupAndBindSymbol
},
169 {"__dyld_NSLookupAndBindSymbolWithHint", (void*)NSLookupAndBindSymbolWithHint
},
170 {"__dyld_NSLookupSymbolInModule", (void*)NSLookupSymbolInModule
},
171 {"__dyld_NSLookupSymbolInImage", (void*)NSLookupSymbolInImage
},
172 {"__dyld_NSMakePrivateModulePublic", (void*)NSMakePrivateModulePublic
},
173 {"__dyld_NSIsSymbolNameDefined", (void*)client_NSIsSymbolNameDefined
},
174 {"__dyld_NSIsSymbolNameDefinedWithHint", (void*)NSIsSymbolNameDefinedWithHint
},
175 {"__dyld_NSIsSymbolNameDefinedInImage", (void*)NSIsSymbolNameDefinedInImage
},
176 {"__dyld_NSNameOfModule", (void*)NSNameOfModule
},
177 {"__dyld_NSLibraryNameForModule", (void*)NSLibraryNameForModule
},
178 {"__dyld_NSAddLibrary", (void*)NSAddLibrary
},
179 {"__dyld_NSAddLibraryWithSearching", (void*)NSAddLibraryWithSearching
},
180 {"__dyld_NSAddImage", (void*)NSAddImage
},
181 {"__dyld_launched_prebound", (void*)_dyld_launched_prebound
},
182 {"__dyld_all_twolevel_modules_prebound", (void*)_dyld_all_twolevel_modules_prebound
},
183 {"__dyld_call_module_initializers_for_dylib", (void*)_dyld_call_module_initializers_for_dylib
},
184 {"__dyld_NSCreateObjectFileImageFromFile", (void*)NSCreateObjectFileImageFromFile
},
185 {"__dyld_NSCreateObjectFileImageFromMemory", (void*)NSCreateObjectFileImageFromMemory
},
186 {"__dyld_NSDestroyObjectFileImage", (void*)NSDestroyObjectFileImage
},
187 {"__dyld_NSLinkModule", (void*)NSLinkModule
},
188 {"__dyld_NSHasModInitObjectFileImage", (void*)NSHasModInitObjectFileImage
},
189 {"__dyld_NSSymbolDefinitionCountInObjectFileImage", (void*)NSSymbolDefinitionCountInObjectFileImage
},
190 {"__dyld_NSSymbolDefinitionNameInObjectFileImage", (void*)NSSymbolDefinitionNameInObjectFileImage
},
191 {"__dyld_NSIsSymbolDefinedInObjectFileImage", (void*)NSIsSymbolDefinedInObjectFileImage
},
192 {"__dyld_NSSymbolReferenceNameInObjectFileImage", (void*)NSSymbolReferenceNameInObjectFileImage
},
193 {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage
},
194 {"__dyld_NSGetSectionDataInObjectFileImage", (void*)NSGetSectionDataInObjectFileImage
},
195 #if OLD_LIBSYSTEM_SUPPORT
196 {"__dyld_link_module", (void*)_dyld_link_module
},
198 #endif //DEPRECATED_APIS_SUPPORTED
205 #if DEPRECATED_APIS_SUPPORTED
207 static void dyldAPIhalt(const char* apiName
, const char* errorMsg
)
209 dyld::log("dyld: %s() error\n", apiName
);
210 dyld::halt(errorMsg
);
213 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
214 inline NSSymbol
SymbolToNSSymbol(const ImageLoader::Symbol
* sym
)
216 return (NSSymbol
)sym
;
218 inline const ImageLoader::Symbol
* NSSymbolToSymbol(NSSymbol sym
)
220 return (const ImageLoader::Symbol
*)sym
;
223 // dyld's abstract type NSModule is implemented as ImageLoader*
224 inline NSModule
ImageLoaderToNSModule(const ImageLoader
* image
)
226 return (NSModule
)image
;
228 inline ImageLoader
* NSModuleToImageLoader(NSModule module
)
230 ImageLoader
* image
= (ImageLoader
*)module
;
231 if ( dyld::validImage(image
) )
236 // actual definition for opaque type
237 struct __NSObjectFileImage
240 const void* imageBaseAddress
; // not used with OFI created from files
241 size_t imageLength
; // not used with OFI created from files
243 static std::vector
<NSObjectFileImage
> sObjectFileImages
;
248 // __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
249 // The contained image is delete in one of two places:
250 // NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
251 // NSDestroyObjectFileImage deletes the image if image is not in list of valid images
256 static void setLastError(NSLinkEditErrors code
, int errnum
, const char* file
, const char* message
)
258 dyld::setErrorMessage(message
);
259 strncpy(sLastErrorFilePath
, file
, 1024);
260 sLastErrorFilePath
[1023] = '\0';
261 sLastErrorFileCode
= code
;
262 sLastErrorNo
= errnum
;
265 #endif // DEPRECATED_APIS_SUPPORTED
268 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
269 * copies the path of the executable into the buffer and returns 0 if the path
270 * was successfully copied in the provided buffer. If the buffer is not large
271 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
272 * Note that _NSGetExecutablePath will return "a path" to the executable not a
273 * "real path" to the executable. That is the path may be a symbolic link and
274 * not the real file. And with deep directories the total bufsize needed could
275 * be more than MAXPATHLEN.
277 int _NSGetExecutablePath(char* buf
, uint32_t *bufsize
)
279 if ( dyld::gLogAPIs
)
280 dyld::log("%s(...)\n", __func__
);
281 const char* exePath
= dyld::getExecutablePath();
282 if(*bufsize
< strlen(exePath
) + 1){
283 *bufsize
= strlen(exePath
) + 1;
286 strcpy(buf
, exePath
);
290 uint32_t _dyld_image_count(void)
292 if ( dyld::gLogAPIs
)
293 dyld::log("%s()\n", __func__
);
294 return dyld::getImageCount();
297 const struct mach_header
* _dyld_get_image_header(uint32_t image_index
)
299 if ( dyld::gLogAPIs
)
300 dyld::log("%s(%u)\n", __func__
, image_index
);
301 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
303 return (struct mach_header
*)image
->machHeader();
308 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index
)
310 if ( dyld::gLogAPIs
)
311 dyld::log("%s(%u)\n", __func__
, image_index
);
312 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
314 return image
->getSlide();
319 intptr_t _dyld_get_image_slide(const struct mach_header
* mh
)
321 if ( dyld::gLogAPIs
)
322 dyld::log("%s(%p)\n", __func__
, mh
);
323 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
325 return image
->getSlide();
331 const char* _dyld_get_image_name(uint32_t image_index
)
333 if ( dyld::gLogAPIs
)
334 dyld::log("%s(%u)\n", __func__
, image_index
);
335 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
337 return image
->getPath();
342 const struct mach_header
* _dyld_get_image_header_containing_address(const void* address
)
344 if ( dyld::gLogAPIs
)
345 dyld::log("%s(%p)\n", __func__
, address
);
346 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
348 return image
->machHeader();
353 void _dyld_register_func_for_add_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
355 if ( dyld::gLogAPIs
)
356 dyld::log("%s(%p)\n", __func__
, (void *)func
);
357 dyld::registerAddCallback(func
);
360 void _dyld_register_func_for_remove_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
362 if ( dyld::gLogAPIs
)
363 dyld::log("%s(%p)\n", __func__
, (void *)func
);
364 dyld::registerRemoveCallback(func
);
369 // called by crt before main() by programs linked with 10.4 or earlier crt1.o
370 static void _dyld_make_delayed_module_initializer_calls()
372 if ( dyld::gLogAPIs
)
373 dyld::log("%s()\n", __func__
);
375 #if SUPPORT_OLD_CRT_INITIALIZATION
376 if ( dyld::gRunInitializersOldWay
)
377 dyld::initializeMainExecutable();
383 #if DEPRECATED_APIS_SUPPORTED
386 // _dyld_call_module_initializers_for_dylib() is the dyld side of
387 // __initialize_Cplusplus() which is in dylib1.o.
388 // It is intended to only be called inside -init rouintes.
389 // -init routines are called before module initializers (what C++
390 // initializers use). Calling __initialize_Cplusplus() in a -init
391 // routine causes the module initializers for an image to be called
392 // which then allows C++ to be used inside a -init routine
394 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
)
396 if ( dyld::gLogAPIs
)
397 dyld::log("__initialize_Cplusplus()\n");
399 // for now, do nothing...
403 void _dyld_lookup_and_bind_fully(const char* symbolName
, void** address
, NSModule
* module
)
405 if ( dyld::gLogAPIs
)
406 dyld::log("%s(\"%s\", %p, %p)\n", __func__
, symbolName
, address
, module
);
408 const ImageLoader::Symbol
* sym
;
409 dyld::clearErrorMessage();
410 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, (const ImageLoader
**)&image
) ) {
412 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
413 if ( address
!= NULL
)
414 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
416 *module
= ImageLoaderToNSModule(image
);
418 catch (const char* msg
) {
419 dyldAPIhalt(__func__
, msg
);
423 // on failure to find symbol return NULLs
424 if ( address
!= NULL
)
431 // Note: This cannot have public name because dyld is built with a static copy of libc.a
432 // which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
433 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module
)
435 if ( dyld::gLogAPIs
)
436 dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName
, address
, module
);
437 const ImageLoader
* image
;
438 const ImageLoader::Symbol
* sym
;
439 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
440 if ( address
!= NULL
)
441 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
443 *module
= ImageLoaderToNSModule(image
);
446 // on failure to find symbol return NULLs
447 if ( address
!= NULL
)
454 void _dyld_lookup_and_bind_with_hint(const char* symbolName
, const char* library_name_hint
, void** address
, NSModule
* module
)
456 if ( dyld::gLogAPIs
)
457 dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__
, symbolName
, library_name_hint
, address
, module
);
458 const ImageLoader
* image
;
459 const ImageLoader::Symbol
* sym
;
460 // Look for library whose path contains the hint. If that fails search everywhere
461 if ( dyld::flatFindExportedSymbolWithHint(symbolName
, library_name_hint
, &sym
, &image
)
462 || dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
463 if ( address
!= NULL
)
464 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
466 *module
= ImageLoaderToNSModule(image
);
469 // on failure to find symbol return NULLs
470 if ( address
!= NULL
)
478 NSSymbol
NSLookupAndBindSymbol(const char *symbolName
)
480 if ( dyld::gLogAPIs
)
481 dyld::log("%s(\"%s\")\n", __func__
, symbolName
);
482 const ImageLoader
* image
;
483 const ImageLoader::Symbol
* sym
;
484 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
485 return SymbolToNSSymbol(sym
);
487 // return NULL on failure
491 NSSymbol
NSLookupAndBindSymbolWithHint(const char* symbolName
, const char* libraryNameHint
)
493 if ( dyld::gLogAPIs
)
494 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
495 const ImageLoader
* image
;
496 const ImageLoader::Symbol
* sym
;
497 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
499 // hint failed, do slow search of all images
500 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
503 return SymbolToNSSymbol(sym
);
505 // return NULL on failure and log
506 if ( dyld::gLogAPIs
)
507 dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__
, symbolName
, libraryNameHint
);
514 static __attribute__((noinline
))
515 const struct mach_header
* addImage(void* callerAddress
, const char* path
, bool search
, bool dontLoad
, bool matchInstallName
, bool abortOnError
)
517 ImageLoader
* image
= NULL
;
518 std::vector
<const char*> rpathsFromCallerImage
;
520 dyld::clearErrorMessage();
521 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
522 // like dlopen, use rpath from caller image and from main executable
523 if ( callerImage
!= NULL
)
524 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
525 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
526 if ( callerImage
!= dyld::mainExecutable() ) {
527 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
529 dyld::LoadContext context
;
530 context
.useSearchPaths
= search
;
531 context
.useFallbackPaths
= search
;
532 context
.useLdLibraryPath
= false;
533 context
.implicitRPath
= false;
534 context
.matchByInstallName
= matchInstallName
;
535 context
.dontLoad
= dontLoad
;
536 context
.mustBeBundle
= false;
537 context
.mustBeDylib
= true;
538 context
.canBePIE
= false;
539 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
540 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
542 image
= load(path
, context
);
543 if ( image
!= NULL
) {
544 if ( context
.matchByInstallName
)
545 image
->setMatchInstallPath(true);
546 dyld::link(image
, false, callersRPaths
);
547 dyld::runInitializers(image
);
548 // images added with NSAddImage() can never be unloaded
549 image
->setNeverUnload();
552 catch (const char* msg
) {
553 dyld::garbageCollectImages();
555 char pathMsg
[strlen(msg
)+strlen(path
)+4];
556 strcpy(pathMsg
, msg
);
557 strcat(pathMsg
, " ");
558 strcat(pathMsg
, path
);
559 dyldAPIhalt("NSAddImage", pathMsg
);
561 // not halting, so set error state for NSLinkEditError to find
562 setLastError(NSLinkEditOtherError
, 0, path
, msg
);
563 free((void*)msg
); // our free() will do nothing if msg is a string literal
566 // free rpaths (getRPaths() malloc'ed each string)
567 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
568 const char* str
= *it
;
574 return image
->machHeader();
578 const struct mach_header
* NSAddImage(const char* path
, uint32_t options
)
580 if ( dyld::gLogAPIs
)
581 dyld::log("%s(\"%s\", 0x%08X)\n", __func__
, path
, options
);
582 const bool dontLoad
= ( (options
& NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
) != 0 );
583 const bool search
= ( (options
& NSADDIMAGE_OPTION_WITH_SEARCHING
) != 0 );
584 const bool matchInstallName
= ( (options
& NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME
) != 0 );
585 const bool abortOnError
= ( (options
& NSADDIMAGE_OPTION_RETURN_ON_ERROR
|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
) == 0 );
586 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
587 return addImage(callerAddress
, path
, search
, dontLoad
, matchInstallName
, abortOnError
);
590 bool NSAddLibrary(const char* path
)
592 if ( dyld::gLogAPIs
)
593 dyld::log("%s(\"%s\")\n", __func__
, path
);
594 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
595 return (addImage(callerAddress
, path
, false, false, false, false) != NULL
);
598 bool NSAddLibraryWithSearching(const char* path
)
600 if ( dyld::gLogAPIs
)
601 dyld::log("%s(\"%s\")\n", __func__
, path
);
602 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
603 return (addImage(callerAddress
, path
, true, false, false, false) != NULL
);
608 //#define NSADDIMAGE_OPTION_NONE 0x0
609 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
610 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
612 bool NSIsSymbolNameDefinedInImage(const struct mach_header
* mh
, const char* symbolName
)
614 if ( dyld::gLogAPIs
)
615 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)mh
, symbolName
);
616 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
617 if ( image
!= NULL
) {
618 if ( image
->findExportedSymbol(symbolName
, true, NULL
) != NULL
)
625 NSSymbol
NSLookupSymbolInImage(const struct mach_header
* mh
, const char* symbolName
, uint32_t options
)
627 if ( dyld::gLogAPIs
)
628 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, mh
, symbolName
, options
);
629 const ImageLoader::Symbol
* symbol
= NULL
;
630 dyld::clearErrorMessage();
631 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
632 if ( image
!= NULL
) {
634 if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY
) {
635 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
637 else if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
) {
638 image
->bindAllLazyPointers(dyld::gLinkContext
, false);
641 catch (const char* msg
) {
642 if ( (options
& NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
) == 0 ) {
643 dyldAPIhalt(__func__
, msg
);
646 symbol
= image
->findExportedSymbol(symbolName
, true, NULL
);
648 if ( dyld::gLogAPIs
&& (symbol
== NULL
) )
649 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__
, mh
, symbolName
, options
);
650 return SymbolToNSSymbol(symbol
);
654 // Note: This cannot have public name because dyld is built with a static copy of libc.a
655 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
656 static bool client_NSIsSymbolNameDefined(const char* symbolName
)
658 if ( dyld::gLogAPIs
)
659 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName
);
660 const ImageLoader
* image
;
661 const ImageLoader::Symbol
* sym
;
662 return dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
665 bool NSIsSymbolNameDefinedWithHint(const char* symbolName
, const char* libraryNameHint
)
667 if ( dyld::gLogAPIs
)
668 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
669 const ImageLoader
* image
;
670 const ImageLoader::Symbol
* sym
;
671 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
673 // hint failed, do slow search of all images
674 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
676 if ( !found
&& dyld::gLogAPIs
)
677 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__
, symbolName
, libraryNameHint
);
681 const char* NSNameOfSymbol(NSSymbol symbol
)
683 if ( dyld::gLogAPIs
)
684 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
685 const char* result
= NULL
;
686 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
688 result
= image
->getExportedSymbolName(NSSymbolToSymbol(symbol
));
692 void* NSAddressOfSymbol(NSSymbol symbol
)
694 if ( dyld::gLogAPIs
)
695 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
696 if ( symbol
== NULL
)
699 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
701 result
= (void*)image
->getExportedSymbolAddress(NSSymbolToSymbol(symbol
), dyld::gLinkContext
);
705 NSModule
NSModuleForSymbol(NSSymbol symbol
)
707 if ( dyld::gLogAPIs
)
708 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
709 NSModule result
= NULL
;
710 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
712 result
= ImageLoaderToNSModule(image
);
719 bool _dyld_all_twolevel_modules_prebound(void)
721 if ( dyld::gLogAPIs
)
722 dyld::log("%s()\n", __func__
);
726 void _dyld_bind_objc_module(const void *objc_module
)
728 if ( dyld::gLogAPIs
)
729 dyld::log("%s(%p)\n", __func__
, objc_module
);
730 // do nothing, with new dyld everything already bound
734 bool _dyld_bind_fully_image_containing_address(const void* address
)
736 if ( dyld::gLogAPIs
)
737 dyld::log("%s(%p)\n", __func__
, address
);
738 dyld::clearErrorMessage();
739 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
740 if ( image
!= NULL
) {
742 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
745 catch (const char* msg
) {
746 dyldAPIhalt(__func__
, msg
);
752 bool _dyld_image_containing_address(const void* address
)
754 if ( dyld::gLogAPIs
)
755 dyld::log("%s(%p)\n", __func__
, address
);
756 ImageLoader
*imageLoader
= dyld::findImageContainingAddress(address
);
757 return (NULL
!= imageLoader
);
760 static NSObjectFileImage
createObjectImageFile(ImageLoader
* image
, const void* address
= NULL
, size_t len
=0)
762 NSObjectFileImage result
= new __NSObjectFileImage();
763 result
->image
= image
;
764 result
->imageBaseAddress
= address
;
765 result
->imageLength
= len
;
766 sObjectFileImages
.push_back(result
);
770 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* pathName
, NSObjectFileImage
*objectFileImage
)
772 if ( dyld::gLogAPIs
)
773 dyld::log("%s(\"%s\", ...)\n", __func__
, pathName
);
775 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
776 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
778 dyld::LoadContext context
;
779 context
.useSearchPaths
= false;
780 context
.useFallbackPaths
= false;
781 context
.useLdLibraryPath
= false;
782 context
.implicitRPath
= false;
783 context
.matchByInstallName
= false;
784 context
.dontLoad
= false;
785 context
.mustBeBundle
= true;
786 context
.mustBeDylib
= false;
787 context
.canBePIE
= false;
788 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
789 context
.rpath
= NULL
; // support not yet implemented
791 ImageLoader
* image
= dyld::load(pathName
, context
);
792 // Note: We DO NOT link the image! NSLinkModule will do that
793 if ( image
!= NULL
) {
794 if ( !image
->isBundle() ) {
795 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
796 return NSObjectFileImageInappropriateFile
;
798 *objectFileImage
= createObjectImageFile(image
);
799 return NSObjectFileImageSuccess
;
802 catch (const char* msg
) {
803 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
804 dyld::garbageCollectImages();
806 return NSObjectFileImageInappropriateFile
;
808 return NSObjectFileImageFailure
;
812 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* address
, size_t size
, NSObjectFileImage
*objectFileImage
)
814 if ( dyld::gLogAPIs
)
815 dyld::log("%s(%p, %lu, %p)\n", __func__
, address
, size
, objectFileImage
);
818 ImageLoader
* image
= dyld::loadFromMemory((const uint8_t*)address
, size
, NULL
);
819 if ( ! image
->isBundle() ) {
820 // this API can only be used with bundles...
821 dyld::garbageCollectImages();
822 return NSObjectFileImageInappropriateFile
;
824 // Note: We DO NOT link the image! NSLinkModule will do that
825 if ( image
!= NULL
) {
826 *objectFileImage
= createObjectImageFile(image
, address
, size
);
827 return NSObjectFileImageSuccess
;
830 catch (const char* msg
) {
832 dyld::garbageCollectImages();
833 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
835 return NSObjectFileImageFailure
;
838 static bool validOFI(NSObjectFileImage objectFileImage
)
840 const int ofiCount
= sObjectFileImages
.size();
841 for (int i
=0; i
< ofiCount
; ++i
) {
842 if ( sObjectFileImages
[i
] == objectFileImage
)
848 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage
)
850 if ( dyld::gLogAPIs
)
851 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
853 if ( validOFI(objectFileImage
) ) {
854 // a failure during NSLinkModule will delete the image
855 if ( objectFileImage
->image
!= NULL
) {
856 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
857 // and we should delete it
858 bool linkedImage
= dyld::validImage(objectFileImage
->image
);
859 if ( ! linkedImage
) {
860 ImageLoader::deleteImage(objectFileImage
->image
);
861 objectFileImage
->image
= NULL
;
865 // remove from list of ofi's
866 for (std::vector
<NSObjectFileImage
>::iterator it
=sObjectFileImages
.begin(); it
!= sObjectFileImages
.end(); it
++) {
867 if ( *it
== objectFileImage
) {
868 sObjectFileImages
.erase(it
);
873 // if object was created from a memory, release that memory
874 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
875 if ( objectFileImage
->imageBaseAddress
!= NULL
) {
877 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 6) ) {
878 size_t sz
= (*dyld::gLibSystemHelpers
->malloc_size
)(objectFileImage
->imageBaseAddress
);
880 (*dyld::gLibSystemHelpers
->free
)((void*)(objectFileImage
->imageBaseAddress
));
885 vm_deallocate(mach_task_self(), (vm_address_t
)objectFileImage
->imageBaseAddress
, objectFileImage
->imageLength
);
889 delete objectFileImage
;
896 bool NSHasModInitObjectFileImage(NSObjectFileImage objectFileImage
)
898 if ( dyld::gLogAPIs
)
899 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
900 return objectFileImage
->image
->needsInitialization();
903 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
905 if ( dyld::gLogAPIs
)
906 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
907 return objectFileImage
->image
->getExportedSymbolCount();
910 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
912 if ( dyld::gLogAPIs
)
913 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
914 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedExportedSymbol(ordinal
);
915 return objectFileImage
->image
->getExportedSymbolName(sym
);
918 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
920 if ( dyld::gLogAPIs
)
921 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
922 return objectFileImage
->image
->getImportedSymbolCount();
925 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
,
926 bool* tentative_definition
)
928 if ( dyld::gLogAPIs
)
929 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
930 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedImportedSymbol(ordinal
);
931 if ( tentative_definition
!= NULL
) {
932 ImageLoader::ReferenceFlags flags
= objectFileImage
->image
->getImportedSymbolInfo(sym
);
933 if ( (flags
& ImageLoader::kTentativeDefinition
) != 0 )
934 *tentative_definition
= true;
936 *tentative_definition
= false;
938 return objectFileImage
->image
->getImportedSymbolName(sym
);
941 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage
,
942 const char* segmentName
, const char* sectionName
, unsigned long* size
)
944 if ( dyld::gLogAPIs
)
945 dyld::log("%s(%p,%s, %s)\n", __func__
, objectFileImage
, segmentName
, sectionName
);
949 if ( objectFileImage
->image
->getSectionContent(segmentName
, sectionName
, &start
, &length
) ) {
959 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage
, const char* symbolName
)
961 if ( dyld::gLogAPIs
)
962 dyld::log("%s(%p,%s)\n", __func__
, objectFileImage
, symbolName
);
963 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->findExportedSymbol(symbolName
, true, NULL
);
964 return ( sym
!= NULL
);
969 NSModule
NSLinkModule(NSObjectFileImage objectFileImage
, const char* moduleName
, uint32_t options
)
971 if ( dyld::gLogAPIs
)
972 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, objectFileImage
, moduleName
, options
);
974 dyld::clearErrorMessage();
976 // NSLinkModule allows a bundle to be link multpile times
977 // each link causes the bundle to be copied to a new address
978 if ( objectFileImage
->image
->isLinked() ) {
979 // already linked, so clone a new one and link it
980 objectFileImage
->image
= dyld::cloneImage(objectFileImage
->image
);
983 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
984 if ( objectFileImage
->image
->getPath() == NULL
) {
985 objectFileImage
->image
->setPath(moduleName
);
986 // <rdar://problem/8812589> dyld has NULL paths in image info array
987 dyld_image_info info
;
988 info
.imageLoadAddress
= objectFileImage
->image
->machHeader();
989 info
.imageFilePath
= moduleName
;
990 info
.imageFileModDate
= 0;
991 addImagesToAllImages(1, &info
);
994 // support private bundles
995 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
996 objectFileImage
->image
->setHideExports();
998 // set up linking options
999 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1001 // load libraries, rebase, bind, to make this image usable
1002 dyld::link(objectFileImage
->image
, forceLazysBound
, ImageLoader::RPathChain(NULL
,NULL
));
1004 // bump reference count to keep this bundle from being garbage collected
1005 objectFileImage
->image
->incrementDlopenReferenceCount();
1007 // run initializers unless magic flag says not to
1008 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1009 dyld::runInitializers(objectFileImage
->image
);
1011 return ImageLoaderToNSModule(objectFileImage
->image
);
1013 catch (const char* msg
) {
1014 dyld::garbageCollectImages();
1015 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1016 dyldAPIhalt(__func__
, msg
);
1017 // not halting, so set error state for NSLinkEditError to find
1018 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1019 // dyld::link() deleted the image so lose our reference
1020 objectFileImage
->image
= NULL
;
1027 #if OLD_LIBSYSTEM_SUPPORT
1028 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1029 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
)
1031 if ( dyld::gLogAPIs
)
1032 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr
, moduleName
, options
); // note name/args translation
1033 ImageLoader
* image
= NULL
;
1034 dyld::clearErrorMessage();
1036 const char* imageName
= moduleName
;
1037 image
= dyld::loadFromMemory((const uint8_t*)object_addr
, object_size
, imageName
);
1039 if ( image
!= NULL
) {
1040 // support private bundles
1041 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1042 image
->setHideExports();
1044 // set up linking options
1045 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1047 // load libraries, rebase, bind, to make this image usable
1048 dyld::link(image
, forceLazysBound
, ImageLoader::RPathChain(NULL
,NULL
));
1050 // run initializers unless magic flag says not to
1051 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1052 dyld::runInitializers(image
);
1055 catch (const char* msg
) {
1056 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1057 dyldAPIhalt("NSLinkModule", msg
);
1058 // not halting, so set error state for NSLinkEditError to find
1059 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1060 // if image was created for this bundle, destroy it
1061 if ( image
!= NULL
) {
1062 dyld::removeImage(image
);
1063 ImageLoader::deleteImage(image
);
1068 return ImageLoaderToNSModule(image
);
1072 NSSymbol
NSLookupSymbolInModule(NSModule module
, const char* symbolName
)
1074 if ( dyld::gLogAPIs
)
1075 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)module
, symbolName
);
1076 ImageLoader
* image
= NSModuleToImageLoader(module
);
1077 if ( image
== NULL
)
1079 return SymbolToNSSymbol(image
->findExportedSymbol(symbolName
, false, NULL
));
1082 const char* NSNameOfModule(NSModule module
)
1084 if ( dyld::gLogAPIs
)
1085 dyld::log("%s(%p)\n", __func__
, module
);
1086 ImageLoader
* image
= NSModuleToImageLoader(module
);
1087 if ( image
== NULL
)
1089 return image
->getPath();
1092 const char* NSLibraryNameForModule(NSModule module
)
1094 if ( dyld::gLogAPIs
)
1095 dyld::log("%s(%p)\n", __func__
, module
);
1096 ImageLoader
* image
= NSModuleToImageLoader(module
);
1097 if ( image
== NULL
)
1099 return image
->getPath();
1102 bool NSUnLinkModule(NSModule module
, uint32_t options
)
1104 if ( dyld::gLogAPIs
)
1105 dyld::log("%s(%p, 0x%08X)\n", __func__
, module
, options
);
1106 if ( module
== NULL
)
1108 ImageLoader
* image
= NSModuleToImageLoader(module
);
1109 if ( image
== NULL
)
1111 dyld::removeImage(image
);
1113 if ( (options
& NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
) != 0 )
1114 image
->setLeaveMapped();
1116 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1118 // Only delete image if there is no ofi referencing it
1119 // That means the ofi was destroyed after linking, so no one is left to delete this image
1120 const int ofiCount
= sObjectFileImages
.size();
1122 for (int i
=0; i
< ofiCount
; ++i
) {
1123 NSObjectFileImage ofi
= sObjectFileImages
[i
];
1124 if ( ofi
->image
== image
)
1128 ImageLoader::deleteImage(image
);
1133 // internal name and parameters do not match public name and parameters...
1134 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
)
1136 if ( dyld::gLogAPIs
)
1137 dyld::log("NSLinkEditErrorHandlers()\n");
1139 dyld::registerUndefinedHandler((dyld::UndefinedHandler
)undefined
);
1140 // no support for multiple or linkedit handlers
1146 void NSLinkEditError(NSLinkEditErrors
* c
, int* errorNumber
, const char** fileName
, const char** errorString
)
1149 *c
= sLastErrorFileCode
;
1150 *errorNumber
= sLastErrorNo
;
1151 *fileName
= sLastErrorFilePath
;
1152 *errorString
= dyld::getErrorMessage();
1157 static void _dyld_register_binding_handler(void * (*bindingHandler
)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions
)
1159 if ( dyld::gLogAPIs
)
1160 dyld::log("%s()\n", __func__
);
1161 dyld::gLinkContext
.bindingHandler
= bindingHandler
;
1162 dyld::gLinkContext
.bindingOptions
= bindingOptions
;
1165 #endif //DEPRECATED_APIS_SUPPORTED
1168 // Call by fork() in libSystem after the kernel trap is done on the child side
1169 void _dyld_fork_child()
1171 if ( dyld::gLogAPIs
)
1172 dyld::log("%s()\n", __func__
);
1173 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1174 // in libSystem for the child of a fork. But dyld is built with a static copy
1175 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1177 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1178 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1180 extern mach_port_t mach_task_self_
;
1181 mach_task_self_
= task_self_trap();
1183 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1184 // page is not copied on fork. <rdar://problem/6797342>
1185 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1186 dyld_all_image_infos
.coreSymbolicationShmPage
= NULL
;
1187 // for safety, make sure child starts with clean systemOrderFlag
1188 dyld_all_image_infos
.systemOrderFlag
= 0;
1193 typedef void (*MonitorProc
)(char *lowpc
, char *highpc
);
1195 static void monInitCallback(ImageLoader
* image
, void* userData
)
1197 MonitorProc proc
= (MonitorProc
)userData
;
1200 if ( image
->getSectionContent("__TEXT", "__text", &start
, &length
) ) {
1201 proc((char*)start
, (char*)start
+length
);
1206 // _dyld_moninit is called from profiling runtime routine moninit().
1207 // dyld calls back with the range of each __TEXT/__text section in every
1210 void _dyld_moninit(MonitorProc proc
)
1212 dyld::forEachImageDo(&monInitCallback
, (void*)proc
);
1215 #if DEPRECATED_APIS_SUPPORTED
1216 // returns true if prebinding was used in main executable
1217 bool _dyld_launched_prebound()
1219 if ( dyld::gLogAPIs
)
1220 dyld::log("%s()\n", __func__
);
1222 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1223 return dyld::mainExecutablePrebound();
1228 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1229 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1230 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1231 // flag on the image for this module. If the module was found and it was
1232 // private then everything worked and TRUE is returned else FALSE is returned.
1234 static bool NSMakePrivateModulePublic(NSModule module
)
1236 ImageLoader
* image
= NSModuleToImageLoader(module
);
1237 if ( image
!= NULL
) {
1238 if ( image
->hasHiddenExports() ) {
1239 image
->setHideExports(false);
1246 #endif // DEPRECATED_APIS_SUPPORTED
1248 bool lookupDyldFunction(const char* name
, uintptr_t* address
)
1250 for (const dyld_func
* p
= dyld_funcs
; p
->name
!= NULL
; ++p
) {
1251 if ( strcmp(p
->name
, name
) == 0 ) {
1252 if( p
->implementation
== unimplemented
)
1253 dyld::log("unimplemented dyld function: %s\n", p
->name
);
1254 *address
= (uintptr_t)p
->implementation
;
1263 static void registerThreadHelpers(const dyld::LibSystemHelpers
* helpers
)
1265 dyld::gLibSystemHelpers
= helpers
;
1267 // let gdb know it is safe to run code in inferior that might call malloc()
1268 dyld_all_image_infos
.libSystemInitialized
= true;
1271 if ( helpers
->version
>= 5 ) {
1272 // create key use by dyld exception handling
1274 int result
= helpers
->pthread_key_create(&key
, NULL
);
1276 __Unwind_SjLj_SetThreadKey(key
);
1282 static void dlerrorClear()
1284 if ( dyld::gLibSystemHelpers
!= NULL
) {
1285 // first char of buffer is flag whether string (starting at second char) is valid
1286 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1292 static void dlerrorSet(const char* msg
)
1294 if ( dyld::gLibSystemHelpers
!= NULL
) {
1295 // first char of buffer is flag whether string (starting at second char) is valid
1296 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(strlen(msg
)+2);
1298 strcpy(&buffer
[1], msg
);
1303 bool dlopen_preflight(const char* path
)
1305 if ( dyld::gLogAPIs
)
1306 dyld::log("%s(%s)\n", __func__
, path
);
1310 #if DYLD_SHARED_CACHE_SUPPORT
1311 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1312 // if requested path is to something in the dyld shared cache, always succeed
1313 if ( dyld::inSharedCache(path
) )
1317 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
1319 bool result
= false;
1320 std::vector
<const char*> rpathsFromCallerImage
;
1322 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1323 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1324 // for dlopen, use rpath from caller image and from main executable
1325 if ( callerImage
!= NULL
)
1326 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1327 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1328 if ( callerImage
!= dyld::mainExecutable() ) {
1329 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1332 ImageLoader
* image
= NULL
;
1333 const bool leafName
= (strchr(path
, '/') == NULL
);
1334 const bool absolutePath
= (path
[0] == '/');
1335 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1336 char canonicalPath
[PATH_MAX
];
1337 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1339 // make path canonical if it contains a // or ./
1340 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1341 const char* lastSlash
= strrchr(path
, '/');
1342 char dirPath
[PATH_MAX
];
1343 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1344 dirPath
[lastSlash
-path
] = '\0';
1345 if ( realpath(dirPath
, canonicalPath
) ) {
1346 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1347 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1348 // if all fit in buffer, use new canonical path
1349 path
= canonicalPath
;
1356 dyld::LoadContext context
;
1357 context
.useSearchPaths
= true;
1358 context
.useFallbackPaths
= leafName
; // a partial path implies don't use fallback paths
1359 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1360 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1361 context
.matchByInstallName
= true;
1362 context
.dontLoad
= false;
1363 context
.mustBeBundle
= false;
1364 context
.mustBeDylib
= false;
1365 context
.canBePIE
= true;
1366 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1367 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1369 image
= load(path
, context
);
1370 if ( image
!= NULL
) {
1371 dyld::preflight(image
, callersRPaths
); // image object deleted by dyld::preflight()
1375 catch (const char* msg
) {
1376 const char* str
= dyld::mkstringf("dlopen_preflight(%s): %s", path
, msg
);
1379 free((void*)msg
); // our free() will do nothing if msg is a string literal
1381 // free rpaths (getRPaths() malloc'ed each string)
1382 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1383 const char* str
= *it
;
1386 CRSetCrashLogMessage(NULL
);
1391 void* dlopen(const char* path
, int mode
)
1393 if ( dyld::gLogAPIs
)
1394 dyld::log("%s(%s, 0x%08X)\n", __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1398 // passing NULL for path means return magic object
1399 if ( path
== NULL
) {
1400 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1401 if ( (mode
& RTLD_FIRST
) != 0 )
1402 return RTLD_MAIN_ONLY
;
1404 return RTLD_DEFAULT
;
1407 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1408 bool lockHeld
= false;
1409 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 4) ) {
1410 dyld::gLibSystemHelpers
->acquireGlobalDyldLock();
1411 CRSetCrashLogMessage("dyld: in dlopen()");
1415 void* result
= NULL
;
1416 ImageLoader
* image
= NULL
;
1417 std::vector
<const char*> rpathsFromCallerImage
;
1419 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1420 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1421 // for dlopen, use rpath from caller image and from main executable
1422 if ( callerImage
!= NULL
)
1423 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1424 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1425 if ( callerImage
!= dyld::mainExecutable() ) {
1426 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1429 const bool leafName
= (strchr(path
, '/') == NULL
);
1430 const bool absolutePath
= (path
[0] == '/');
1431 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1432 char canonicalPath
[PATH_MAX
];
1433 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1435 // make path canonical if it contains a // or ./
1436 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1437 const char* lastSlash
= strrchr(path
, '/');
1438 char dirPath
[PATH_MAX
];
1439 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1440 dirPath
[lastSlash
-path
] = '\0';
1441 if ( realpath(dirPath
, canonicalPath
) ) {
1442 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1443 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1444 // if all fit in buffer, use new canonical path
1445 path
= canonicalPath
;
1452 dyld::LoadContext context
;
1453 context
.useSearchPaths
= true;
1454 context
.useFallbackPaths
= leafName
; // a partial path means no fallback paths
1455 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1456 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1457 context
.matchByInstallName
= true;
1458 context
.dontLoad
= ( (mode
& RTLD_NOLOAD
) != 0 );
1459 context
.mustBeBundle
= false;
1460 context
.mustBeDylib
= false;
1461 context
.canBePIE
= true;
1462 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1463 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1465 image
= load(path
, context
);
1466 if ( image
!= NULL
) {
1467 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1468 // this image is not garbage collected
1469 image
->incrementDlopenReferenceCount();
1470 // link in all dependents
1471 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1472 bool alreadyLinked
= image
->isLinked();
1473 bool forceLazysBound
= ( (mode
& RTLD_NOW
) != 0 );
1474 dyld::link(image
, forceLazysBound
, callersRPaths
);
1475 if ( ! alreadyLinked
) {
1476 // only hide exports if image is not already in use
1477 if ( (mode
& RTLD_LOCAL
) != 0 )
1478 image
->setHideExports(true);
1482 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1483 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1484 // The subtle differences are:
1485 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1486 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1487 if ( (mode
& RTLD_NODELETE
) != 0 )
1488 image
->setLeaveMapped();
1490 // release global dyld lock early, this enables initializers to do threaded operations
1492 CRSetCrashLogMessage(NULL
);
1493 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1497 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1498 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1499 // called from within an initializer because it can cause initializers to run
1500 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1501 // to run, then don't use RTLD_NOLOAD.
1502 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1504 dyld::runInitializers(image
);
1507 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1508 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1509 if ( (mode
& RTLD_FIRST
) != 0 )
1510 result
= (void*)(((uintptr_t)image
)|1);
1515 catch (const char* msg
) {
1516 if ( image
!= NULL
) {
1517 // load() succeeded but, link() failed
1518 // back down reference count and do GC
1519 image
->decrementDlopenReferenceCount();
1520 dyld::garbageCollectImages();
1522 const char* str
= dyld::mkstringf("dlopen(%s, %d): %s", path
, mode
, msg
);
1525 free((void*)msg
); // our free() will do nothing if msg is a string literal
1528 // free rpaths (getRPaths() malloc'ed each string)
1529 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1530 const char* str
= *it
;
1534 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1535 if ( (mode
& RTLD_NOLOAD
) && (result
== NULL
) ) {
1536 dlerrorSet("image not already loaded");
1540 CRSetCrashLogMessage(NULL
);
1541 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1548 int dlclose(void* handle
)
1550 if ( dyld::gLogAPIs
)
1551 dyld::log("%s(%p)\n", __func__
, handle
);
1553 // silently accept magic handles for main executable
1554 if ( handle
== RTLD_MAIN_ONLY
)
1556 if ( handle
== RTLD_DEFAULT
)
1559 ImageLoader
* image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1560 if ( dyld::validImage(image
) ) {
1562 // decrement use count
1563 if ( image
->decrementDlopenReferenceCount() ) {
1564 dlerrorSet("dlclose() called too many times");
1567 // remove image if reference count went to zero
1568 dyld::garbageCollectImages();
1572 dlerrorSet("invalid handle passed to dlclose()");
1579 int dladdr(const void* address
, Dl_info
* info
)
1581 if ( dyld::gLogAPIs
)
1582 dyld::log("%s(%p, %p)\n", __func__
, address
, info
);
1584 CRSetCrashLogMessage("dyld: in dladdr()");
1585 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1586 if ( image
!= NULL
) {
1587 info
->dli_fname
= image
->getPath();
1588 info
->dli_fbase
= (void*)image
->machHeader();
1589 if ( address
== info
->dli_fbase
) {
1590 // special case lookup of header
1591 info
->dli_sname
= "__dso_handle";
1592 info
->dli_saddr
= info
->dli_fbase
;
1593 CRSetCrashLogMessage(NULL
);
1594 return 1; // success
1596 // find closest symbol in the image
1597 info
->dli_sname
= image
->findClosestSymbol(address
, (const void**)&info
->dli_saddr
);
1598 if ( info
->dli_sname
!= NULL
) {
1599 if ( info
->dli_sname
[0] == '_' )
1600 info
->dli_sname
= info
->dli_sname
+1; // strip off leading underscore
1601 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1602 CRSetCrashLogMessage(NULL
);
1603 return 1; // success
1605 info
->dli_sname
= NULL
;
1606 info
->dli_saddr
= NULL
;
1607 CRSetCrashLogMessage(NULL
);
1608 return 1; // success
1610 CRSetCrashLogMessage(NULL
);
1611 return 0; // failure
1617 if ( dyld::gLogAPIs
)
1618 dyld::log("%s()\n", __func__
);
1620 if ( dyld::gLibSystemHelpers
!= NULL
) {
1621 // first char of buffer is flag whether string (starting at second char) is valid
1622 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1623 if ( buffer
[0] != '\0' ) { // if valid buffer
1624 buffer
[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1625 return &buffer
[1]; // return message
1631 void* dlsym(void* handle
, const char* symbolName
)
1633 if ( dyld::gLogAPIs
)
1634 dyld::log("%s(%p, %s)\n", __func__
, handle
, symbolName
);
1636 CRSetCrashLogMessage("dyld: in dlsym()");
1639 const ImageLoader
* image
;
1640 const ImageLoader::Symbol
* sym
;
1642 // dlsym() assumes symbolName passed in is same as in C source code
1643 // dyld assumes all symbol names have an underscore prefix
1644 char underscoredName
[strlen(symbolName
)+2];
1645 underscoredName
[0] = '_';
1646 strcpy(&underscoredName
[1], symbolName
);
1648 // magic "search all" handle
1649 if ( handle
== RTLD_DEFAULT
) {
1650 if ( dyld::flatFindExportedSymbol(underscoredName
, &sym
, &image
) ) {
1651 CRSetCrashLogMessage(NULL
);
1652 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1654 const char* str
= dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName
);
1657 CRSetCrashLogMessage(NULL
);
1661 // magic "search only main executable" handle
1662 if ( handle
== RTLD_MAIN_ONLY
) {
1663 image
= dyld::mainExecutable();
1664 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1665 if ( sym
!= NULL
) {
1666 CRSetCrashLogMessage(NULL
);
1667 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1669 const char* str
= dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName
);
1672 CRSetCrashLogMessage(NULL
);
1676 // magic "search what I would see" handle
1677 if ( handle
== RTLD_NEXT
) {
1679 // <rdar://problem/7628929> work around for llvmgcc bug
1680 void* fa
= __builtin_frame_address(0);
1683 void* callerAddress
= *((void**)(((int)fa
)+8));
1685 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1687 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1688 sym
= callerImage
->findExportedSymbolInDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // don't search image, but do search what it links against
1689 if ( sym
!= NULL
) {
1690 CRSetCrashLogMessage(NULL
);
1691 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1693 const char* str
= dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName
);
1696 CRSetCrashLogMessage(NULL
);
1699 // magic "search me, then what I would see" handle
1700 if ( handle
== RTLD_SELF
) {
1701 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1702 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1703 sym
= callerImage
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1704 if ( sym
!= NULL
) {
1705 CRSetCrashLogMessage(NULL
);
1706 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1708 const char* str
= dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName
);
1711 CRSetCrashLogMessage(NULL
);
1715 image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1716 if ( dyld::validImage(image
) ) {
1717 if ( (((uintptr_t)handle
) & 1) != 0 )
1718 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1720 sym
= image
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1722 if ( sym
!= NULL
) {
1723 CRSetCrashLogMessage(NULL
);
1724 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1726 const char* str
= dyld::mkstringf("dlsym(%p, %s): symbol not found", handle
, symbolName
);
1731 dlerrorSet("invalid handle passed to dlsym()");
1733 CRSetCrashLogMessage(NULL
);
1746 const struct dyld_all_image_infos
* _dyld_get_all_image_infos()
1748 return &dyld_all_image_infos
;
1752 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
)
1754 //if ( dyld::gLogAPIs )
1755 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
1757 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
1758 if ( image
!= NULL
) {
1759 image
->getUnwindInfo(info
);
1767 void dyld_register_image_state_change_handler(dyld_image_states state
, bool batch
,
1768 dyld_image_state_change_handler handler
)
1770 if ( dyld::gLogAPIs
)
1771 dyld::log("%s(%d, %d, %p)\n", __func__
, state
, batch
, handler
);
1773 dyld::registerImageStateBatchChangeHandler(state
, handler
);
1775 dyld::registerImageStateSingleChangeHandler(state
, handler
);
1778 const char* dyld_image_path_containing_address(const void* address
)
1780 if ( dyld::gLogAPIs
)
1781 dyld::log("%s(%p)\n", __func__
, address
);
1783 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1784 if ( image
!= NULL
)
1785 return image
->getPath();
1791 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1792 bool dyld_shared_cache_some_image_overridden()
1794 return dyld::gSharedCacheOverridden
;