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
61 // deprecated APIs are still availble on Mac OS X, but not on iPhone OS
62 #if __IPHONE_OS_VERSION_MIN_REQUIRED
63 #define DEPRECATED_APIS_SUPPORTED 0
65 #define DEPRECATED_APIS_SUPPORTED 1
69 #if DEPRECATED_APIS_SUPPORTED
70 static char sLastErrorFilePath
[1024];
71 static NSLinkEditErrors sLastErrorFileCode
;
72 static int sLastErrorNo
;
75 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
76 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
77 // This conditional keeps support for old libSystem's which needed some help implementing the API's
78 #define OLD_LIBSYSTEM_SUPPORT (__ppc__ || __i386__)
81 // The following functions have no prototype in any header. They are special cases
82 // where _dyld_func_lookup() is used directly.
83 static void _dyld_fork_child();
84 static void _dyld_make_delayed_module_initializer_calls();
85 static void registerThreadHelpers(const dyld::LibSystemHelpers
*);
86 #if DEPRECATED_APIS_SUPPORTED
87 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
);
88 #if OLD_LIBSYSTEM_SUPPORT
89 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
);
91 static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions
);
92 static bool NSMakePrivateModulePublic(NSModule
module);
93 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
);
95 // The following functions are dyld API's, but since dyld links with a static copy of libc.a
96 // the public name cannot be used.
97 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module);
98 static bool client_NSIsSymbolNameDefined(const char* symbolName
);
99 #endif // DEPRECATED_APIS_SUPPORTED
100 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
);
102 static void unimplemented()
104 dyld::halt("unimplemented dyld function\n");
109 void* implementation
;
112 static struct dyld_func dyld_funcs
[] = {
113 {"__dyld_register_func_for_add_image", (void*)_dyld_register_func_for_add_image
},
114 {"__dyld_register_func_for_remove_image", (void*)_dyld_register_func_for_remove_image
},
115 {"__dyld_dladdr", (void*)dladdr
},
116 {"__dyld_dlclose", (void*)dlclose
},
117 {"__dyld_dlerror", (void*)dlerror
},
118 {"__dyld_dlopen", (void*)dlopen
},
119 {"__dyld_dlsym", (void*)dlsym
},
120 {"__dyld_dlopen_preflight", (void*)dlopen_preflight
},
121 {"__dyld_get_image_header_containing_address", (void*)_dyld_get_image_header_containing_address
},
122 {"__dyld_image_count", (void*)_dyld_image_count
},
123 {"__dyld_get_image_header", (void*)_dyld_get_image_header
},
124 {"__dyld_get_image_vmaddr_slide", (void*)_dyld_get_image_vmaddr_slide
},
125 {"__dyld_get_image_name", (void*)_dyld_get_image_name
},
126 {"__dyld_get_image_slide", (void*)_dyld_get_image_slide
},
127 {"__dyld__NSGetExecutablePath", (void*)_NSGetExecutablePath
},
130 {"__dyld_dyld_register_image_state_change_handler", (void*)dyld_register_image_state_change_handler
},
131 {"__dyld_register_thread_helpers", (void*)registerThreadHelpers
},
132 {"__dyld_fork_child", (void*)_dyld_fork_child
},
133 {"__dyld_moninit", (void*)_dyld_moninit
},
134 {"__dyld_make_delayed_module_initializer_calls", (void*)_dyld_make_delayed_module_initializer_calls
},
135 {"__dyld_get_all_image_infos", (void*)_dyld_get_all_image_infos
},
137 {"__dyld_find_unwind_sections", (void*)client_dyld_find_unwind_sections
},
139 #if __i386__ || __x86_64__
140 {"__dyld_fast_stub_entry", (void*)dyld::fastBindLazySymbol
},
142 {"__dyld_image_path_containing_address", (void*)dyld_image_path_containing_address
},
145 #if DEPRECATED_APIS_SUPPORTED
146 {"__dyld_lookup_and_bind", (void*)client_dyld_lookup_and_bind
},
147 {"__dyld_lookup_and_bind_with_hint", (void*)_dyld_lookup_and_bind_with_hint
},
148 {"__dyld_lookup_and_bind_fully", (void*)_dyld_lookup_and_bind_fully
},
149 {"__dyld_install_handlers", (void*)_dyld_install_handlers
},
150 {"__dyld_link_edit_error", (void*)NSLinkEditError
},
151 {"__dyld_unlink_module", (void*)NSUnLinkModule
},
152 {"__dyld_bind_objc_module", (void*)_dyld_bind_objc_module
},
153 {"__dyld_bind_fully_image_containing_address", (void*)_dyld_bind_fully_image_containing_address
},
154 {"__dyld_image_containing_address", (void*)_dyld_image_containing_address
},
155 {"__dyld_register_binding_handler", (void*)_dyld_register_binding_handler
},
156 {"__dyld_NSNameOfSymbol", (void*)NSNameOfSymbol
},
157 {"__dyld_NSAddressOfSymbol", (void*)NSAddressOfSymbol
},
158 {"__dyld_NSModuleForSymbol", (void*)NSModuleForSymbol
},
159 {"__dyld_NSLookupAndBindSymbol", (void*)NSLookupAndBindSymbol
},
160 {"__dyld_NSLookupAndBindSymbolWithHint", (void*)NSLookupAndBindSymbolWithHint
},
161 {"__dyld_NSLookupSymbolInModule", (void*)NSLookupSymbolInModule
},
162 {"__dyld_NSLookupSymbolInImage", (void*)NSLookupSymbolInImage
},
163 {"__dyld_NSMakePrivateModulePublic", (void*)NSMakePrivateModulePublic
},
164 {"__dyld_NSIsSymbolNameDefined", (void*)client_NSIsSymbolNameDefined
},
165 {"__dyld_NSIsSymbolNameDefinedWithHint", (void*)NSIsSymbolNameDefinedWithHint
},
166 {"__dyld_NSIsSymbolNameDefinedInImage", (void*)NSIsSymbolNameDefinedInImage
},
167 {"__dyld_NSNameOfModule", (void*)NSNameOfModule
},
168 {"__dyld_NSLibraryNameForModule", (void*)NSLibraryNameForModule
},
169 {"__dyld_NSAddLibrary", (void*)NSAddLibrary
},
170 {"__dyld_NSAddLibraryWithSearching", (void*)NSAddLibraryWithSearching
},
171 {"__dyld_NSAddImage", (void*)NSAddImage
},
172 {"__dyld_launched_prebound", (void*)_dyld_launched_prebound
},
173 {"__dyld_all_twolevel_modules_prebound", (void*)_dyld_all_twolevel_modules_prebound
},
174 {"__dyld_call_module_initializers_for_dylib", (void*)_dyld_call_module_initializers_for_dylib
},
175 {"__dyld_NSCreateObjectFileImageFromFile", (void*)NSCreateObjectFileImageFromFile
},
176 {"__dyld_NSCreateObjectFileImageFromMemory", (void*)NSCreateObjectFileImageFromMemory
},
177 {"__dyld_NSDestroyObjectFileImage", (void*)NSDestroyObjectFileImage
},
178 {"__dyld_NSLinkModule", (void*)NSLinkModule
},
179 {"__dyld_NSHasModInitObjectFileImage", (void*)NSHasModInitObjectFileImage
},
180 {"__dyld_NSSymbolDefinitionCountInObjectFileImage", (void*)NSSymbolDefinitionCountInObjectFileImage
},
181 {"__dyld_NSSymbolDefinitionNameInObjectFileImage", (void*)NSSymbolDefinitionNameInObjectFileImage
},
182 {"__dyld_NSIsSymbolDefinedInObjectFileImage", (void*)NSIsSymbolDefinedInObjectFileImage
},
183 {"__dyld_NSSymbolReferenceNameInObjectFileImage", (void*)NSSymbolReferenceNameInObjectFileImage
},
184 {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage
},
185 {"__dyld_NSGetSectionDataInObjectFileImage", (void*)NSGetSectionDataInObjectFileImage
},
186 #if OLD_LIBSYSTEM_SUPPORT
187 {"__dyld_link_module", (void*)_dyld_link_module
},
189 #endif //DEPRECATED_APIS_SUPPORTED
196 #if DEPRECATED_APIS_SUPPORTED
198 static void dyldAPIhalt(const char* apiName
, const char* errorMsg
)
200 dyld::log("dyld: %s() error\n", apiName
);
201 dyld::halt(errorMsg
);
204 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
205 inline NSSymbol
SymbolToNSSymbol(const ImageLoader::Symbol
* sym
)
207 return (NSSymbol
)sym
;
209 inline const ImageLoader::Symbol
* NSSymbolToSymbol(NSSymbol sym
)
211 return (const ImageLoader::Symbol
*)sym
;
214 // dyld's abstract type NSModule is implemented as ImageLoader*
215 inline NSModule
ImageLoaderToNSModule(const ImageLoader
* image
)
217 return (NSModule
)image
;
219 inline ImageLoader
* NSModuleToImageLoader(NSModule
module)
221 ImageLoader
* image
= (ImageLoader
*)module;
222 if ( dyld::validImage(image
) )
227 // actual definition for opaque type
228 struct __NSObjectFileImage
231 const void* imageBaseAddress
; // not used with OFI created from files
232 size_t imageLength
; // not used with OFI created from files
234 static std::vector
<NSObjectFileImage
> sObjectFileImages
;
239 // __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
240 // The contained image is delete in one of two places:
241 // NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
242 // NSDestroyObjectFileImage deletes the image if image is not in list of valid images
247 static void setLastError(NSLinkEditErrors code
, int errnum
, const char* file
, const char* message
)
249 dyld::setErrorMessage(message
);
250 strncpy(sLastErrorFilePath
, file
, 1024);
251 sLastErrorFilePath
[1023] = '\0';
252 sLastErrorFileCode
= code
;
253 sLastErrorNo
= errnum
;
256 #endif // DEPRECATED_APIS_SUPPORTED
259 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
260 * copies the path of the executable into the buffer and returns 0 if the path
261 * was successfully copied in the provided buffer. If the buffer is not large
262 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
263 * Note that _NSGetExecutablePath will return "a path" to the executable not a
264 * "real path" to the executable. That is the path may be a symbolic link and
265 * not the real file. And with deep directories the total bufsize needed could
266 * be more than MAXPATHLEN.
268 int _NSGetExecutablePath(char* buf
, uint32_t *bufsize
)
270 if ( dyld::gLogAPIs
)
271 dyld::log("%s(...)\n", __func__
);
272 const char* exePath
= dyld::getExecutablePath();
273 if(*bufsize
< strlen(exePath
) + 1){
274 *bufsize
= strlen(exePath
) + 1;
277 strcpy(buf
, exePath
);
281 uint32_t _dyld_image_count(void)
283 if ( dyld::gLogAPIs
)
284 dyld::log("%s()\n", __func__
);
285 return dyld::getImageCount();
288 const struct mach_header
* _dyld_get_image_header(uint32_t image_index
)
290 if ( dyld::gLogAPIs
)
291 dyld::log("%s(%u)\n", __func__
, image_index
);
292 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
294 return (struct mach_header
*)image
->machHeader();
299 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index
)
301 if ( dyld::gLogAPIs
)
302 dyld::log("%s(%u)\n", __func__
, image_index
);
303 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
305 return image
->getSlide();
310 intptr_t _dyld_get_image_slide(const struct mach_header
* mh
)
312 if ( dyld::gLogAPIs
)
313 dyld::log("%s(%p)\n", __func__
, mh
);
314 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
316 return image
->getSlide();
322 const char* _dyld_get_image_name(uint32_t image_index
)
324 if ( dyld::gLogAPIs
)
325 dyld::log("%s(%u)\n", __func__
, image_index
);
326 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
328 return image
->getPath();
333 const struct mach_header
* _dyld_get_image_header_containing_address(const void* address
)
335 if ( dyld::gLogAPIs
)
336 dyld::log("%s(%p)\n", __func__
, address
);
337 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
339 return image
->machHeader();
344 void _dyld_register_func_for_add_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
346 if ( dyld::gLogAPIs
)
347 dyld::log("%s(%p)\n", __func__
, (void *)func
);
348 dyld::registerAddCallback(func
);
351 void _dyld_register_func_for_remove_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
353 if ( dyld::gLogAPIs
)
354 dyld::log("%s(%p)\n", __func__
, (void *)func
);
355 dyld::registerRemoveCallback(func
);
360 // called by crt before main() by programs linked with 10.4 or earlier crt1.o
361 static void _dyld_make_delayed_module_initializer_calls()
363 if ( dyld::gLogAPIs
)
364 dyld::log("%s()\n", __func__
);
366 #if SUPPORT_OLD_CRT_INITIALIZATION
367 if ( dyld::gRunInitializersOldWay
)
368 dyld::initializeMainExecutable();
374 #if DEPRECATED_APIS_SUPPORTED
377 // _dyld_call_module_initializers_for_dylib() is the dyld side of
378 // __initialize_Cplusplus() which is in dylib1.o.
379 // It is intended to only be called inside -init rouintes.
380 // -init routines are called before module initializers (what C++
381 // initializers use). Calling __initialize_Cplusplus() in a -init
382 // routine causes the module initializers for an image to be called
383 // which then allows C++ to be used inside a -init routine
385 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
)
387 if ( dyld::gLogAPIs
)
388 dyld::log("__initialize_Cplusplus()\n");
390 // for now, do nothing...
394 void _dyld_lookup_and_bind_fully(const char* symbolName
, void** address
, NSModule
* module)
396 if ( dyld::gLogAPIs
)
397 dyld::log("%s(\"%s\", %p, %p)\n", __func__
, symbolName
, address
, module);
399 const ImageLoader::Symbol
* sym
;
400 dyld::clearErrorMessage();
401 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, (const ImageLoader
**)&image
) ) {
403 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
404 if ( address
!= NULL
)
405 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
407 *module = ImageLoaderToNSModule(image
);
409 catch (const char* msg
) {
410 dyldAPIhalt(__func__
, msg
);
414 // on failure to find symbol return NULLs
415 if ( address
!= NULL
)
422 // Note: This cannot have public name because dyld is built with a static copy of libc.a
423 // which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
424 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module)
426 if ( dyld::gLogAPIs
)
427 dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName
, address
, module);
428 const ImageLoader
* image
;
429 const ImageLoader::Symbol
* sym
;
430 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
431 if ( address
!= NULL
)
432 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
434 *module = ImageLoaderToNSModule(image
);
437 // on failure to find symbol return NULLs
438 if ( address
!= NULL
)
445 void _dyld_lookup_and_bind_with_hint(const char* symbolName
, const char* library_name_hint
, void** address
, NSModule
* module)
447 if ( dyld::gLogAPIs
)
448 dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__
, symbolName
, library_name_hint
, address
, module);
449 const ImageLoader
* image
;
450 const ImageLoader::Symbol
* sym
;
451 // Look for library whose path contains the hint. If that fails search everywhere
452 if ( dyld::flatFindExportedSymbolWithHint(symbolName
, library_name_hint
, &sym
, &image
)
453 || 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
)
469 NSSymbol
NSLookupAndBindSymbol(const char *symbolName
)
471 if ( dyld::gLogAPIs
)
472 dyld::log("%s(\"%s\")\n", __func__
, symbolName
);
473 const ImageLoader
* image
;
474 const ImageLoader::Symbol
* sym
;
475 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
476 return SymbolToNSSymbol(sym
);
478 // return NULL on failure
482 NSSymbol
NSLookupAndBindSymbolWithHint(const char* symbolName
, const char* libraryNameHint
)
484 if ( dyld::gLogAPIs
)
485 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
486 const ImageLoader
* image
;
487 const ImageLoader::Symbol
* sym
;
488 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
490 // hint failed, do slow search of all images
491 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
494 return SymbolToNSSymbol(sym
);
496 // return NULL on failure and log
497 if ( dyld::gLogAPIs
)
498 dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__
, symbolName
, libraryNameHint
);
505 static __attribute__((noinline
))
506 const struct mach_header
* addImage(void* callerAddress
, const char* path
, bool search
, bool dontLoad
, bool matchInstallName
, bool abortOnError
)
508 ImageLoader
* image
= NULL
;
509 std::vector
<const char*> rpathsFromCallerImage
;
511 dyld::clearErrorMessage();
512 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
513 // like dlopen, use rpath from caller image and from main executable
514 if ( callerImage
!= NULL
)
515 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
516 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
517 if ( callerImage
!= dyld::mainExecutable() ) {
518 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
520 dyld::LoadContext context
;
521 context
.useSearchPaths
= search
;
522 context
.useFallbackPaths
= search
;
523 context
.useLdLibraryPath
= false;
524 context
.implicitRPath
= false;
525 context
.matchByInstallName
= matchInstallName
;
526 context
.dontLoad
= dontLoad
;
527 context
.mustBeBundle
= false;
528 context
.mustBeDylib
= true;
529 context
.canBePIE
= false;
530 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
531 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
533 image
= load(path
, context
);
534 if ( image
!= NULL
) {
535 if ( context
.matchByInstallName
)
536 image
->setMatchInstallPath(true);
537 dyld::link(image
, false, callersRPaths
);
538 dyld::runInitializers(image
);
539 // images added with NSAddImage() can never be unloaded
540 image
->setNeverUnload();
543 catch (const char* msg
) {
544 dyld::garbageCollectImages();
546 char pathMsg
[strlen(msg
)+strlen(path
)+4];
547 strcpy(pathMsg
, msg
);
548 strcat(pathMsg
, " ");
549 strcat(pathMsg
, path
);
550 dyldAPIhalt("NSAddImage", pathMsg
);
552 // not halting, so set error state for NSLinkEditError to find
553 setLastError(NSLinkEditOtherError
, 0, path
, msg
);
554 free((void*)msg
); // our free() will do nothing if msg is a string literal
557 // free rpaths (getRPaths() malloc'ed each string)
558 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
559 const char* str
= *it
;
565 return image
->machHeader();
569 const struct mach_header
* NSAddImage(const char* path
, uint32_t options
)
571 if ( dyld::gLogAPIs
)
572 dyld::log("%s(\"%s\", 0x%08X)\n", __func__
, path
, options
);
573 const bool dontLoad
= ( (options
& NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
) != 0 );
574 const bool search
= ( (options
& NSADDIMAGE_OPTION_WITH_SEARCHING
) != 0 );
575 const bool matchInstallName
= ( (options
& NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME
) != 0 );
576 const bool abortOnError
= ( (options
& NSADDIMAGE_OPTION_RETURN_ON_ERROR
|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
) == 0 );
577 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
578 return addImage(callerAddress
, path
, search
, dontLoad
, matchInstallName
, abortOnError
);
581 bool NSAddLibrary(const char* path
)
583 if ( dyld::gLogAPIs
)
584 dyld::log("%s(\"%s\")\n", __func__
, path
);
585 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
586 return (addImage(callerAddress
, path
, false, false, false, false) != NULL
);
589 bool NSAddLibraryWithSearching(const char* path
)
591 if ( dyld::gLogAPIs
)
592 dyld::log("%s(\"%s\")\n", __func__
, path
);
593 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
594 return (addImage(callerAddress
, path
, true, false, false, false) != NULL
);
599 //#define NSADDIMAGE_OPTION_NONE 0x0
600 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
601 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
603 bool NSIsSymbolNameDefinedInImage(const struct mach_header
* mh
, const char* symbolName
)
605 if ( dyld::gLogAPIs
)
606 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)mh
, symbolName
);
607 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
608 if ( image
!= NULL
) {
609 if ( image
->findExportedSymbol(symbolName
, true, NULL
) != NULL
)
616 NSSymbol
NSLookupSymbolInImage(const struct mach_header
* mh
, const char* symbolName
, uint32_t options
)
618 if ( dyld::gLogAPIs
)
619 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, mh
, symbolName
, options
);
620 const ImageLoader::Symbol
* symbol
= NULL
;
621 dyld::clearErrorMessage();
622 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
623 if ( image
!= NULL
) {
625 if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY
) {
626 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
628 else if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
) {
629 image
->bindAllLazyPointers(dyld::gLinkContext
, false);
632 catch (const char* msg
) {
633 if ( (options
& NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
) == 0 ) {
634 dyldAPIhalt(__func__
, msg
);
637 symbol
= image
->findExportedSymbol(symbolName
, true, NULL
);
639 if ( dyld::gLogAPIs
&& (symbol
== NULL
) )
640 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__
, mh
, symbolName
, options
);
641 return SymbolToNSSymbol(symbol
);
645 // Note: This cannot have public name because dyld is built with a static copy of libc.a
646 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
647 static bool client_NSIsSymbolNameDefined(const char* symbolName
)
649 if ( dyld::gLogAPIs
)
650 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName
);
651 const ImageLoader
* image
;
652 const ImageLoader::Symbol
* sym
;
653 return dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
656 bool NSIsSymbolNameDefinedWithHint(const char* symbolName
, const char* libraryNameHint
)
658 if ( dyld::gLogAPIs
)
659 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
660 const ImageLoader
* image
;
661 const ImageLoader::Symbol
* sym
;
662 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
664 // hint failed, do slow search of all images
665 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
667 if ( !found
&& dyld::gLogAPIs
)
668 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__
, symbolName
, libraryNameHint
);
672 const char* NSNameOfSymbol(NSSymbol symbol
)
674 if ( dyld::gLogAPIs
)
675 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
676 const char* result
= NULL
;
677 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
679 result
= image
->getExportedSymbolName(NSSymbolToSymbol(symbol
));
683 void* NSAddressOfSymbol(NSSymbol symbol
)
685 if ( dyld::gLogAPIs
)
686 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
687 if ( symbol
== NULL
)
690 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
692 result
= (void*)image
->getExportedSymbolAddress(NSSymbolToSymbol(symbol
), dyld::gLinkContext
);
696 NSModule
NSModuleForSymbol(NSSymbol symbol
)
698 if ( dyld::gLogAPIs
)
699 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
700 NSModule result
= NULL
;
701 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
703 result
= ImageLoaderToNSModule(image
);
710 bool _dyld_all_twolevel_modules_prebound(void)
712 if ( dyld::gLogAPIs
)
713 dyld::log("%s()\n", __func__
);
717 void _dyld_bind_objc_module(const void *objc_module
)
719 if ( dyld::gLogAPIs
)
720 dyld::log("%s(%p)\n", __func__
, objc_module
);
721 // do nothing, with new dyld everything already bound
725 bool _dyld_bind_fully_image_containing_address(const void* address
)
727 if ( dyld::gLogAPIs
)
728 dyld::log("%s(%p)\n", __func__
, address
);
729 dyld::clearErrorMessage();
730 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
731 if ( image
!= NULL
) {
733 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
736 catch (const char* msg
) {
737 dyldAPIhalt(__func__
, msg
);
743 bool _dyld_image_containing_address(const void* address
)
745 if ( dyld::gLogAPIs
)
746 dyld::log("%s(%p)\n", __func__
, address
);
747 ImageLoader
*imageLoader
= dyld::findImageContainingAddress(address
);
748 return (NULL
!= imageLoader
);
751 static NSObjectFileImage
createObjectImageFile(ImageLoader
* image
, const void* address
= NULL
, size_t len
=0)
753 NSObjectFileImage result
= new __NSObjectFileImage();
754 result
->image
= image
;
755 result
->imageBaseAddress
= address
;
756 result
->imageLength
= len
;
757 sObjectFileImages
.push_back(result
);
761 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* pathName
, NSObjectFileImage
*objectFileImage
)
763 if ( dyld::gLogAPIs
)
764 dyld::log("%s(\"%s\", ...)\n", __func__
, pathName
);
766 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
767 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
769 dyld::LoadContext context
;
770 context
.useSearchPaths
= false;
771 context
.useFallbackPaths
= false;
772 context
.useLdLibraryPath
= false;
773 context
.implicitRPath
= false;
774 context
.matchByInstallName
= false;
775 context
.dontLoad
= false;
776 context
.mustBeBundle
= true;
777 context
.mustBeDylib
= false;
778 context
.canBePIE
= false;
779 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
780 context
.rpath
= NULL
; // support not yet implemented
782 ImageLoader
* image
= dyld::load(pathName
, context
);
783 // Note: We DO NOT link the image! NSLinkModule will do that
784 if ( image
!= NULL
) {
785 if ( !image
->isBundle() ) {
786 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
787 return NSObjectFileImageInappropriateFile
;
789 *objectFileImage
= createObjectImageFile(image
);
790 return NSObjectFileImageSuccess
;
793 catch (const char* msg
) {
794 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
795 dyld::garbageCollectImages();
797 return NSObjectFileImageInappropriateFile
;
799 return NSObjectFileImageFailure
;
803 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* address
, size_t size
, NSObjectFileImage
*objectFileImage
)
805 if ( dyld::gLogAPIs
)
806 dyld::log("%s(%p, %lu, %p)\n", __func__
, address
, size
, objectFileImage
);
809 ImageLoader
* image
= dyld::loadFromMemory((const uint8_t*)address
, size
, NULL
);
810 if ( ! image
->isBundle() ) {
811 // this API can only be used with bundles...
812 dyld::garbageCollectImages();
813 return NSObjectFileImageInappropriateFile
;
815 // Note: We DO NOT link the image! NSLinkModule will do that
816 if ( image
!= NULL
) {
817 *objectFileImage
= createObjectImageFile(image
, address
, size
);
818 return NSObjectFileImageSuccess
;
821 catch (const char* msg
) {
823 dyld::garbageCollectImages();
824 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
826 return NSObjectFileImageFailure
;
829 static bool validOFI(NSObjectFileImage objectFileImage
)
831 const int ofiCount
= sObjectFileImages
.size();
832 for (int i
=0; i
< ofiCount
; ++i
) {
833 if ( sObjectFileImages
[i
] == objectFileImage
)
839 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage
)
841 if ( dyld::gLogAPIs
)
842 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
844 if ( validOFI(objectFileImage
) ) {
845 // a failure during NSLinkModule will delete the image
846 if ( objectFileImage
->image
!= NULL
) {
847 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
848 // and we should delete it
849 bool linkedImage
= dyld::validImage(objectFileImage
->image
);
850 if ( ! linkedImage
) {
851 ImageLoader::deleteImage(objectFileImage
->image
);
852 objectFileImage
->image
= NULL
;
856 // remove from list of ofi's
857 for (std::vector
<NSObjectFileImage
>::iterator it
=sObjectFileImages
.begin(); it
!= sObjectFileImages
.end(); it
++) {
858 if ( *it
== objectFileImage
) {
859 sObjectFileImages
.erase(it
);
864 // if object was created from a memory, release that memory
865 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
866 if ( objectFileImage
->imageBaseAddress
!= NULL
) {
868 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 6) ) {
869 size_t sz
= (*dyld::gLibSystemHelpers
->malloc_size
)(objectFileImage
->imageBaseAddress
);
871 (*dyld::gLibSystemHelpers
->free
)((void*)(objectFileImage
->imageBaseAddress
));
876 vm_deallocate(mach_task_self(), (vm_address_t
)objectFileImage
->imageBaseAddress
, objectFileImage
->imageLength
);
880 delete objectFileImage
;
887 bool NSHasModInitObjectFileImage(NSObjectFileImage objectFileImage
)
889 if ( dyld::gLogAPIs
)
890 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
891 return objectFileImage
->image
->needsInitialization();
894 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
896 if ( dyld::gLogAPIs
)
897 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
898 return objectFileImage
->image
->getExportedSymbolCount();
901 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
903 if ( dyld::gLogAPIs
)
904 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
905 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedExportedSymbol(ordinal
);
906 return objectFileImage
->image
->getExportedSymbolName(sym
);
909 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
911 if ( dyld::gLogAPIs
)
912 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
913 return objectFileImage
->image
->getImportedSymbolCount();
916 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
,
917 bool* tentative_definition
)
919 if ( dyld::gLogAPIs
)
920 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
921 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedImportedSymbol(ordinal
);
922 if ( tentative_definition
!= NULL
) {
923 ImageLoader::ReferenceFlags flags
= objectFileImage
->image
->getImportedSymbolInfo(sym
);
924 if ( (flags
& ImageLoader::kTentativeDefinition
) != 0 )
925 *tentative_definition
= true;
927 *tentative_definition
= false;
929 return objectFileImage
->image
->getImportedSymbolName(sym
);
932 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage
,
933 const char* segmentName
, const char* sectionName
, unsigned long* size
)
935 if ( dyld::gLogAPIs
)
936 dyld::log("%s(%p,%s, %s)\n", __func__
, objectFileImage
, segmentName
, sectionName
);
940 if ( objectFileImage
->image
->getSectionContent(segmentName
, sectionName
, &start
, &length
) ) {
950 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage
, const char* symbolName
)
952 if ( dyld::gLogAPIs
)
953 dyld::log("%s(%p,%s)\n", __func__
, objectFileImage
, symbolName
);
954 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->findExportedSymbol(symbolName
, true, NULL
);
955 return ( sym
!= NULL
);
960 NSModule
NSLinkModule(NSObjectFileImage objectFileImage
, const char* moduleName
, uint32_t options
)
962 if ( dyld::gLogAPIs
)
963 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, objectFileImage
, moduleName
, options
);
965 dyld::clearErrorMessage();
967 // NSLinkModule allows a bundle to be link multpile times
968 // each link causes the bundle to be copied to a new address
969 if ( objectFileImage
->image
->isLinked() ) {
970 // already linked, so clone a new one and link it
971 objectFileImage
->image
= dyld::cloneImage(objectFileImage
->image
);
974 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
975 if ( objectFileImage
->image
->getPath() == NULL
)
976 objectFileImage
->image
->setPath(moduleName
);
978 // support private bundles
979 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
980 objectFileImage
->image
->setHideExports();
982 // set up linking options
983 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
985 // load libraries, rebase, bind, to make this image usable
986 dyld::link(objectFileImage
->image
, forceLazysBound
, ImageLoader::RPathChain(NULL
,NULL
));
988 // bump reference count to keep this bundle from being garbage collected
989 objectFileImage
->image
->incrementDlopenReferenceCount();
991 // run initializers unless magic flag says not to
992 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
993 dyld::runInitializers(objectFileImage
->image
);
995 return ImageLoaderToNSModule(objectFileImage
->image
);
997 catch (const char* msg
) {
998 dyld::garbageCollectImages();
999 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1000 dyldAPIhalt(__func__
, msg
);
1001 // not halting, so set error state for NSLinkEditError to find
1002 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1003 // dyld::link() deleted the image so lose our reference
1004 objectFileImage
->image
= NULL
;
1011 #if OLD_LIBSYSTEM_SUPPORT
1012 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1013 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
)
1015 if ( dyld::gLogAPIs
)
1016 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr
, moduleName
, options
); // note name/args translation
1017 ImageLoader
* image
= NULL
;
1018 dyld::clearErrorMessage();
1020 const char* imageName
= moduleName
;
1021 image
= dyld::loadFromMemory((const uint8_t*)object_addr
, object_size
, imageName
);
1023 if ( image
!= NULL
) {
1024 // support private bundles
1025 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1026 image
->setHideExports();
1028 // set up linking options
1029 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1031 // load libraries, rebase, bind, to make this image usable
1032 dyld::link(image
, forceLazysBound
, ImageLoader::RPathChain(NULL
,NULL
));
1034 // run initializers unless magic flag says not to
1035 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1036 dyld::runInitializers(image
);
1039 catch (const char* msg
) {
1040 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1041 dyldAPIhalt("NSLinkModule", msg
);
1042 // not halting, so set error state for NSLinkEditError to find
1043 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1044 // if image was created for this bundle, destroy it
1045 if ( image
!= NULL
) {
1046 dyld::removeImage(image
);
1047 ImageLoader::deleteImage(image
);
1052 return ImageLoaderToNSModule(image
);
1056 NSSymbol
NSLookupSymbolInModule(NSModule
module, const char* symbolName
)
1058 if ( dyld::gLogAPIs
)
1059 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)module, symbolName
);
1060 ImageLoader
* image
= NSModuleToImageLoader(module);
1061 if ( image
== NULL
)
1063 return SymbolToNSSymbol(image
->findExportedSymbol(symbolName
, false, NULL
));
1066 const char* NSNameOfModule(NSModule
module)
1068 if ( dyld::gLogAPIs
)
1069 dyld::log("%s(%p)\n", __func__
, module);
1070 ImageLoader
* image
= NSModuleToImageLoader(module);
1071 if ( image
== NULL
)
1073 return image
->getPath();
1076 const char* NSLibraryNameForModule(NSModule
module)
1078 if ( dyld::gLogAPIs
)
1079 dyld::log("%s(%p)\n", __func__
, module);
1080 ImageLoader
* image
= NSModuleToImageLoader(module);
1081 if ( image
== NULL
)
1083 return image
->getPath();
1086 bool NSUnLinkModule(NSModule
module, uint32_t options
)
1088 if ( dyld::gLogAPIs
)
1089 dyld::log("%s(%p, 0x%08X)\n", __func__
, module, options
);
1090 if ( module == NULL
)
1092 ImageLoader
* image
= NSModuleToImageLoader(module);
1093 if ( image
== NULL
)
1095 dyld::removeImage(image
);
1097 if ( (options
& NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
) != 0 )
1098 image
->setLeaveMapped();
1100 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1102 // Only delete image if there is no ofi referencing it
1103 // That means the ofi was destroyed after linking, so no one is left to delete this image
1104 const int ofiCount
= sObjectFileImages
.size();
1106 for (int i
=0; i
< ofiCount
; ++i
) {
1107 NSObjectFileImage ofi
= sObjectFileImages
[i
];
1108 if ( ofi
->image
== image
)
1112 ImageLoader::deleteImage(image
);
1117 // internal name and parameters do not match public name and parameters...
1118 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
)
1120 if ( dyld::gLogAPIs
)
1121 dyld::log("NSLinkEditErrorHandlers()\n");
1123 dyld::registerUndefinedHandler((dyld::UndefinedHandler
)undefined
);
1124 // no support for multiple or linkedit handlers
1130 void NSLinkEditError(NSLinkEditErrors
* c
, int* errorNumber
, const char** fileName
, const char** errorString
)
1133 *c
= sLastErrorFileCode
;
1134 *errorNumber
= sLastErrorNo
;
1135 *fileName
= sLastErrorFilePath
;
1136 *errorString
= dyld::getErrorMessage();
1141 static void _dyld_register_binding_handler(void * (*bindingHandler
)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions
)
1143 if ( dyld::gLogAPIs
)
1144 dyld::log("%s()\n", __func__
);
1145 dyld::gLinkContext
.bindingHandler
= bindingHandler
;
1146 dyld::gLinkContext
.bindingOptions
= bindingOptions
;
1149 #endif //DEPRECATED_APIS_SUPPORTED
1152 // Call by fork() in libSystem after the kernel trap is done on the child side
1153 static void _dyld_fork_child()
1155 if ( dyld::gLogAPIs
)
1156 dyld::log("%s()\n", __func__
);
1157 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1158 // in libSystem for the child of a fork. But dyld is built with a static copy
1159 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1161 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1162 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1164 extern mach_port_t mach_task_self_
;
1165 mach_task_self_
= task_self_trap();
1167 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1168 // page is not copied on fork. <rdar://problem/6797342>
1169 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1170 dyld_all_image_infos
.coreSymbolicationShmPage
= NULL
;
1171 // for safety, make sure child starts with clean systemOrderFlag
1172 dyld_all_image_infos
.systemOrderFlag
= 0;
1177 typedef void (*MonitorProc
)(char *lowpc
, char *highpc
);
1179 static void monInitCallback(ImageLoader
* image
, void* userData
)
1181 MonitorProc proc
= (MonitorProc
)userData
;
1184 if ( image
->getSectionContent("__TEXT", "__text", &start
, &length
) ) {
1185 proc((char*)start
, (char*)start
+length
);
1190 // _dyld_moninit is called from profiling runtime routine moninit().
1191 // dyld calls back with the range of each __TEXT/__text section in every
1194 void _dyld_moninit(MonitorProc proc
)
1196 dyld::forEachImageDo(&monInitCallback
, (void*)proc
);
1199 #if DEPRECATED_APIS_SUPPORTED
1200 // returns true if prebinding was used in main executable
1201 bool _dyld_launched_prebound()
1203 if ( dyld::gLogAPIs
)
1204 dyld::log("%s()\n", __func__
);
1206 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1207 return dyld::mainExecutablePrebound();
1212 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1213 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1214 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1215 // flag on the image for this module. If the module was found and it was
1216 // private then everything worked and TRUE is returned else FALSE is returned.
1218 static bool NSMakePrivateModulePublic(NSModule
module)
1220 ImageLoader
* image
= NSModuleToImageLoader(module);
1221 if ( image
!= NULL
) {
1222 if ( image
->hasHiddenExports() ) {
1223 image
->setHideExports(false);
1230 #endif // DEPRECATED_APIS_SUPPORTED
1232 bool lookupDyldFunction(const char* name
, uintptr_t* address
)
1234 for (const dyld_func
* p
= dyld_funcs
; p
->name
!= NULL
; ++p
) {
1235 if ( strcmp(p
->name
, name
) == 0 ) {
1236 if( p
->implementation
== unimplemented
)
1237 dyld::log("unimplemented dyld function: %s\n", p
->name
);
1238 *address
= (uintptr_t)p
->implementation
;
1246 static void registerThreadHelpers(const dyld::LibSystemHelpers
* helpers
)
1248 dyld::gLibSystemHelpers
= helpers
;
1250 // let gdb know it is safe to run code in inferior that might call malloc()
1251 dyld_all_image_infos
.libSystemInitialized
= true;
1255 static void dlerrorClear()
1257 if ( dyld::gLibSystemHelpers
!= NULL
) {
1258 // first char of buffer is flag whether string (starting at second char) is valid
1259 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1265 static void dlerrorSet(const char* msg
)
1267 if ( dyld::gLibSystemHelpers
!= NULL
) {
1268 // first char of buffer is flag whether string (starting at second char) is valid
1269 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(strlen(msg
)+2);
1271 strcpy(&buffer
[1], msg
);
1276 bool dlopen_preflight(const char* path
)
1278 if ( dyld::gLogAPIs
)
1279 dyld::log("%s(%s)\n", __func__
, path
);
1283 #if DYLD_SHARED_CACHE_SUPPORT
1284 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1285 // if requested path is to something in the dyld shared cache, always succeed
1286 if ( dyld::inSharedCache(path
) )
1290 bool result
= false;
1291 std::vector
<const char*> rpathsFromCallerImage
;
1293 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1294 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1295 // for dlopen, use rpath from caller image and from main executable
1296 if ( callerImage
!= NULL
)
1297 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1298 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1299 if ( callerImage
!= dyld::mainExecutable() ) {
1300 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1303 ImageLoader
* image
= NULL
;
1304 const bool leafName
= (strchr(path
, '/') == NULL
);
1305 const bool absolutePath
= (path
[0] == '/');
1306 dyld::LoadContext context
;
1307 context
.useSearchPaths
= true;
1308 context
.useFallbackPaths
= leafName
; // a partial path implies don't use fallback paths
1309 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1310 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1311 context
.matchByInstallName
= true;
1312 context
.dontLoad
= false;
1313 context
.mustBeBundle
= false;
1314 context
.mustBeDylib
= false;
1315 context
.canBePIE
= true;
1316 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1317 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1319 image
= load(path
, context
);
1320 if ( image
!= NULL
) {
1321 dyld::preflight(image
, callersRPaths
); // image object deleted by dyld::preflight()
1325 catch (const char* msg
) {
1326 const char* str
= dyld::mkstringf("dlopen_preflight(%s): %s", path
, msg
);
1329 free((void*)msg
); // our free() will do nothing if msg is a string literal
1331 // free rpaths (getRPaths() malloc'ed each string)
1332 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1333 const char* str
= *it
;
1340 void* dlopen(const char* path
, int mode
)
1342 if ( dyld::gLogAPIs
)
1343 dyld::log("%s(%s, 0x%08X)\n", __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1347 // passing NULL for path means return magic object
1348 if ( path
== NULL
) {
1349 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1350 if ( (mode
& RTLD_FIRST
) != 0 )
1351 return RTLD_MAIN_ONLY
;
1353 return RTLD_DEFAULT
;
1356 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1357 bool lockHeld
= false;
1358 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 4) ) {
1359 dyld::gLibSystemHelpers
->acquireGlobalDyldLock();
1363 void* result
= NULL
;
1364 ImageLoader
* image
= NULL
;
1365 std::vector
<const char*> rpathsFromCallerImage
;
1367 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1368 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1369 // for dlopen, use rpath from caller image and from main executable
1370 if ( callerImage
!= NULL
)
1371 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1372 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1373 if ( callerImage
!= dyld::mainExecutable() ) {
1374 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1377 const bool leafName
= (strchr(path
, '/') == NULL
);
1378 const bool absolutePath
= (path
[0] == '/');
1379 dyld::LoadContext context
;
1380 context
.useSearchPaths
= true;
1381 context
.useFallbackPaths
= leafName
; // a partial path means no fallback paths
1382 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1383 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1384 context
.matchByInstallName
= true;
1385 context
.dontLoad
= ( (mode
& RTLD_NOLOAD
) != 0 );
1386 context
.mustBeBundle
= false;
1387 context
.mustBeDylib
= false;
1388 context
.canBePIE
= true;
1389 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1390 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1392 image
= load(path
, context
);
1393 if ( image
!= NULL
) {
1394 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1395 // this image is not garbage collected
1396 image
->incrementDlopenReferenceCount();
1397 // link in all dependents
1398 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1399 bool alreadyLinked
= image
->isLinked();
1400 bool forceLazysBound
= ( (mode
& RTLD_NOW
) != 0 );
1401 dyld::link(image
, forceLazysBound
, callersRPaths
);
1402 if ( ! alreadyLinked
) {
1403 // only hide exports if image is not already in use
1404 if ( (mode
& RTLD_LOCAL
) != 0 )
1405 image
->setHideExports(true);
1409 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1410 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1411 // The subtle differences are:
1412 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1413 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1414 if ( (mode
& RTLD_NODELETE
) != 0 )
1415 image
->setLeaveMapped();
1417 // release global dyld lock early, this enables initializers to do threaded operations
1419 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1423 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1424 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1425 // called from within an initializer because it can cause initializers to run
1426 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1427 // to run, then don't use RTLD_NOLOAD.
1428 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1430 dyld::runInitializers(image
);
1433 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1434 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1435 if ( (mode
& RTLD_FIRST
) != 0 )
1436 result
= (void*)(((uintptr_t)image
)|1);
1441 catch (const char* msg
) {
1442 if ( image
!= NULL
) {
1443 // load() succeeded but, link() failed
1444 // back down reference count and do GC
1445 image
->decrementDlopenReferenceCount();
1446 dyld::garbageCollectImages();
1448 const char* str
= dyld::mkstringf("dlopen(%s, %d): %s", path
, mode
, msg
);
1451 free((void*)msg
); // our free() will do nothing if msg is a string literal
1454 // free rpaths (getRPaths() malloc'ed each string)
1455 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1456 const char* str
= *it
;
1460 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1461 if ( (mode
& RTLD_NOLOAD
) && (result
== NULL
) ) {
1462 dlerrorSet("image not already loaded");
1466 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1472 int dlclose(void* handle
)
1474 if ( dyld::gLogAPIs
)
1475 dyld::log("%s(%p)\n", __func__
, handle
);
1477 // silently accept magic handles for main executable
1478 if ( handle
== RTLD_MAIN_ONLY
)
1480 if ( handle
== RTLD_DEFAULT
)
1483 ImageLoader
* image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1484 if ( dyld::validImage(image
) ) {
1486 // decrement use count
1487 if ( image
->decrementDlopenReferenceCount() ) {
1488 dlerrorSet("dlclose() called too many times");
1491 // remove image if reference count went to zero
1492 dyld::garbageCollectImages();
1496 dlerrorSet("invalid handle passed to dlclose()");
1503 int dladdr(const void* address
, Dl_info
* info
)
1505 if ( dyld::gLogAPIs
)
1506 dyld::log("%s(%p, %p)\n", __func__
, address
, info
);
1508 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1509 if ( image
!= NULL
) {
1510 info
->dli_fname
= image
->getPath();
1511 info
->dli_fbase
= (void*)image
->machHeader();
1512 if ( address
== info
->dli_fbase
) {
1513 // special case lookup of header
1514 info
->dli_sname
= "__dso_handle";
1515 info
->dli_saddr
= info
->dli_fbase
;
1516 return 1; // success
1518 // find closest symbol in the image
1519 info
->dli_sname
= image
->findClosestSymbol(address
, (const void**)&info
->dli_saddr
);
1520 if ( info
->dli_sname
!= NULL
) {
1521 if ( info
->dli_sname
[0] == '_' )
1522 info
->dli_sname
= info
->dli_sname
+1; // strip off leading underscore
1523 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1524 return 1; // success
1526 info
->dli_sname
= NULL
;
1527 info
->dli_saddr
= NULL
;
1528 return 1; // success
1530 return 0; // failure
1536 if ( dyld::gLogAPIs
)
1537 dyld::log("%s()\n", __func__
);
1539 if ( dyld::gLibSystemHelpers
!= NULL
) {
1540 // first char of buffer is flag whether string (starting at second char) is valid
1541 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1542 if ( buffer
[0] != '\0' ) { // if valid buffer
1543 buffer
[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1544 return &buffer
[1]; // return message
1550 void* dlsym(void* handle
, const char* symbolName
)
1552 if ( dyld::gLogAPIs
)
1553 dyld::log("%s(%p, %s)\n", __func__
, handle
, symbolName
);
1557 const ImageLoader
* image
;
1558 const ImageLoader::Symbol
* sym
;
1560 // dlsym() assumes symbolName passed in is same as in C source code
1561 // dyld assumes all symbol names have an underscore prefix
1562 char underscoredName
[strlen(symbolName
)+2];
1563 underscoredName
[0] = '_';
1564 strcpy(&underscoredName
[1], symbolName
);
1566 // magic "search all" handle
1567 if ( handle
== RTLD_DEFAULT
) {
1568 if ( dyld::flatFindExportedSymbol(underscoredName
, &sym
, &image
) ) {
1569 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1571 const char* str
= dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName
);
1577 // magic "search only main executable" handle
1578 if ( handle
== RTLD_MAIN_ONLY
) {
1579 image
= dyld::mainExecutable();
1580 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1581 if ( sym
!= NULL
) {
1582 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1584 const char* str
= dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName
);
1590 // magic "search what I would see" handle
1591 if ( handle
== RTLD_NEXT
) {
1592 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1593 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1594 sym
= callerImage
->findExportedSymbolInDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // don't search image, but do search what it links against
1595 if ( sym
!= NULL
) {
1596 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1598 const char* str
= dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName
);
1603 // magic "search me, then what I would see" handle
1604 if ( handle
== RTLD_SELF
) {
1605 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1606 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1607 sym
= callerImage
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1608 if ( sym
!= NULL
) {
1609 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1611 const char* str
= dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName
);
1617 image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1618 if ( dyld::validImage(image
) ) {
1619 if ( (((uintptr_t)handle
) & 1) != 0 )
1620 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1622 sym
= image
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1624 if ( sym
!= NULL
) {
1625 return (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
1627 const char* str
= dyld::mkstringf("dlsym(%p, %s): symbol not found", handle
, symbolName
);
1632 dlerrorSet("invalid handle passed to dlsym()");
1646 const struct dyld_all_image_infos
* _dyld_get_all_image_infos()
1648 return &dyld_all_image_infos
;
1652 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
)
1654 //if ( dyld::gLogAPIs )
1655 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
1657 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
1658 if ( image
!= NULL
) {
1659 image
->getUnwindInfo(info
);
1667 void dyld_register_image_state_change_handler(dyld_image_states state
, bool batch
,
1668 dyld_image_state_change_handler handler
)
1670 if ( dyld::gLogAPIs
)
1671 dyld::log("%s(%d, %d, %p)\n", __func__
, state
, batch
, handler
);
1673 dyld::registerImageStateBatchChangeHandler(state
, handler
);
1675 dyld::registerImageStateSingleChangeHandler(state
, handler
);
1679 const char* dyld_image_path_containing_address(const void* address
)
1681 if ( dyld::gLogAPIs
)
1682 dyld::log("%s(%p)\n", __func__
, address
);
1684 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1685 if ( image
!= NULL
)
1686 return image
->getPath();