1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2005 Apple Computer, 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>
34 #include <mach/mach.h>
36 #include <sys/sysctl.h>
38 extern "C" mach_port_name_t
task_self_trap(void); // can't include <System/mach/mach_traps.h> because it is missing extern C
40 #include "mach-o/dyld_gdb.h"
41 #include "mach-o/dyld.h"
42 #include "mach-o/dyld_priv.h"
45 #include "ImageLoader.h"
47 #include "dyldLibSystemThreadHelpers.h"
49 static char sLastErrorFilePath
[1024];
50 static NSLinkEditErrors sLastErrorFileCode
;
51 static int sLastErrorNo
;
54 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
55 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
56 // This conditional keeps support for old libSystem's which needed some help implementing the API's
57 #define OLD_LIBSYSTEM_SUPPORT 1
60 // The following functions have no prototype in any header. They are special cases
61 // where _dyld_func_lookup() is used directly.
62 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
);
63 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
);
64 static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions
);
65 static void _dyld_fork_prepare();
66 static void _dyld_fork_parent();
67 static void _dyld_fork_child();
68 static void _dyld_fork_child_final();
69 static void _dyld_make_delayed_module_initializer_calls();
70 static void _dyld_mod_term_funcs();
71 static bool NSMakePrivateModulePublic(NSModule
module);
72 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
);
73 static void registerThreadHelpers(const dyld::ThreadingHelpers
*);
74 static void _dyld_update_prebinding(int pathCount
, const char* paths
[], uint32_t flags
);
75 static const struct dyld_all_image_infos
* _dyld_get_all_image_infos();
77 // The following functions are dyld API's, but since dyld links with a static copy of libc.a
78 // the public name cannot be used.
79 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module);
80 static bool client_NSIsSymbolNameDefined(const char* symbolName
);
83 static void unimplemented()
85 dyld::halt("unimplemented dyld function\n");
93 static struct dyld_func dyld_funcs
[] = {
94 {"__dyld_image_count", (void*)_dyld_image_count
},
95 {"__dyld_get_image_header", (void*)_dyld_get_image_header
},
96 {"__dyld_get_image_vmaddr_slide", (void*)_dyld_get_image_vmaddr_slide
},
97 {"__dyld_get_image_name", (void*)_dyld_get_image_name
},
98 {"__dyld_lookup_and_bind", (void*)client_dyld_lookup_and_bind
},
99 {"__dyld_lookup_and_bind_with_hint", (void*)_dyld_lookup_and_bind_with_hint
},
100 {"__dyld_lookup_and_bind_objc", (void*)unimplemented
},
101 {"__dyld_lookup_and_bind_fully", (void*)_dyld_lookup_and_bind_fully
},
102 {"__dyld_install_handlers", (void*)_dyld_install_handlers
},
103 {"__dyld_link_edit_error", (void*)NSLinkEditError
},
104 #if OLD_LIBSYSTEM_SUPPORT
105 {"__dyld_link_module", (void*)_dyld_link_module
},
107 {"__dyld_unlink_module", (void*)NSUnLinkModule
},
108 {"__dyld_register_func_for_add_image", (void*)_dyld_register_func_for_add_image
},
109 {"__dyld_register_func_for_remove_image", (void*)_dyld_register_func_for_remove_image
},
110 {"__dyld_register_func_for_link_module", (void*)unimplemented
},
111 {"__dyld_register_func_for_unlink_module", (void*)unimplemented
},
112 {"__dyld_register_func_for_replace_module", (void*)unimplemented
},
113 {"__dyld_get_objc_module_sect_for_module", (void*)unimplemented
},
114 {"__dyld_bind_objc_module", (void*)_dyld_bind_objc_module
},
115 {"__dyld_bind_fully_image_containing_address", (void*)_dyld_bind_fully_image_containing_address
},
116 {"__dyld_image_containing_address", (void*)_dyld_image_containing_address
},
117 {"__dyld_get_image_header_containing_address", (void*)_dyld_get_image_header_containing_address
},
118 {"__dyld_moninit", (void*)_dyld_moninit
},
119 {"__dyld_register_binding_handler", (void*)_dyld_register_binding_handler
},
120 {"__dyld_fork_prepare", (void*)_dyld_fork_prepare
},
121 {"__dyld_fork_parent", (void*)_dyld_fork_parent
},
122 {"__dyld_fork_child", (void*)_dyld_fork_child
},
123 {"__dyld_fork_child_final", (void*)_dyld_fork_child_final
},
124 {"__dyld_fork_mach_init", (void*)unimplemented
},
125 {"__dyld_make_delayed_module_initializer_calls",(void*)_dyld_make_delayed_module_initializer_calls
},
126 {"__dyld_NSNameOfSymbol", (void*)NSNameOfSymbol
},
127 {"__dyld_NSAddressOfSymbol", (void*)NSAddressOfSymbol
},
128 {"__dyld_NSModuleForSymbol", (void*)NSModuleForSymbol
},
129 {"__dyld_NSLookupAndBindSymbol", (void*)NSLookupAndBindSymbol
},
130 {"__dyld_NSLookupAndBindSymbolWithHint", (void*)NSLookupAndBindSymbolWithHint
},
131 {"__dyld_NSLookupSymbolInModule", (void*)NSLookupSymbolInModule
},
132 {"__dyld_NSLookupSymbolInImage", (void*)NSLookupSymbolInImage
},
133 {"__dyld_NSMakePrivateModulePublic", (void*)NSMakePrivateModulePublic
},
134 {"__dyld_NSIsSymbolNameDefined", (void*)client_NSIsSymbolNameDefined
},
135 {"__dyld_NSIsSymbolNameDefinedWithHint", (void*)NSIsSymbolNameDefinedWithHint
},
136 {"__dyld_NSIsSymbolNameDefinedInImage", (void*)NSIsSymbolNameDefinedInImage
},
137 {"__dyld_NSNameOfModule", (void*)NSNameOfModule
},
138 {"__dyld_NSLibraryNameForModule", (void*)NSLibraryNameForModule
},
139 {"__dyld_NSAddLibrary", (void*)NSAddLibrary
},
140 {"__dyld_NSAddLibraryWithSearching", (void*)NSAddLibraryWithSearching
},
141 {"__dyld_NSAddImage", (void*)NSAddImage
},
142 {"__dyld__NSGetExecutablePath", (void*)_NSGetExecutablePath
},
143 {"__dyld_launched_prebound", (void*)_dyld_launched_prebound
},
144 {"__dyld_all_twolevel_modules_prebound", (void*)_dyld_all_twolevel_modules_prebound
},
145 {"__dyld_call_module_initializers_for_dylib", (void*)_dyld_call_module_initializers_for_dylib
},
146 {"__dyld_mod_term_funcs", (void*)_dyld_mod_term_funcs
},
147 {"__dyld_install_link_edit_symbol_handlers", (void*)dyld::registerZeroLinkHandlers
},
148 {"__dyld_NSCreateObjectFileImageFromFile", (void*)NSCreateObjectFileImageFromFile
},
149 {"__dyld_NSCreateObjectFileImageFromMemory", (void*)NSCreateObjectFileImageFromMemory
},
150 {"__dyld_NSCreateCoreFileImageFromFile", (void*)unimplemented
},
151 {"__dyld_NSDestroyObjectFileImage", (void*)NSDestroyObjectFileImage
},
152 {"__dyld_NSLinkModule", (void*)NSLinkModule
},
153 {"__dyld_NSHasModInitObjectFileImage", (void*)NSHasModInitObjectFileImage
},
154 {"__dyld_NSSymbolDefinitionCountInObjectFileImage", (void*)NSSymbolDefinitionCountInObjectFileImage
},
155 {"__dyld_NSSymbolDefinitionNameInObjectFileImage", (void*)NSSymbolDefinitionNameInObjectFileImage
},
156 {"__dyld_NSIsSymbolDefinedInObjectFileImage", (void*)NSIsSymbolDefinedInObjectFileImage
},
157 {"__dyld_NSSymbolReferenceNameInObjectFileImage", (void*)NSSymbolReferenceNameInObjectFileImage
},
158 {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage
},
159 {"__dyld_NSGetSectionDataInObjectFileImage", (void*)NSGetSectionDataInObjectFileImage
},
160 {"__dyld_NSFindSectionAndOffsetInObjectFileImage", (void*)NSFindSectionAndOffsetInObjectFileImage
},
161 {"__dyld_register_thread_helpers", (void*)registerThreadHelpers
},
162 {"__dyld_dladdr", (void*)dladdr
},
163 {"__dyld_dlclose", (void*)dlclose
},
164 {"__dyld_dlerror", (void*)dlerror
},
165 {"__dyld_dlopen", (void*)dlopen
},
166 {"__dyld_dlsym", (void*)dlsym
},
167 {"__dyld_update_prebinding", (void*)_dyld_update_prebinding
},
168 {"__dyld_get_all_image_infos", (void*)_dyld_get_all_image_infos
},
174 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
175 inline NSSymbol
SymbolToNSSymbol(const ImageLoader::Symbol
* sym
)
177 return (NSSymbol
)sym
;
179 inline const ImageLoader::Symbol
* NSSymbolToSymbol(NSSymbol sym
)
181 return (const ImageLoader::Symbol
*)sym
;
184 // dyld's abstract type NSModule is implemented as ImageLoader*
185 inline NSModule
ImageLoaderToNSModule(ImageLoader
* image
)
187 return (NSModule
)image
;
189 inline ImageLoader
* NSModuleToImageLoader(NSModule
module)
191 ImageLoader
* image
= (ImageLoader
*)module;
192 if ( dyld::validImage(image
) )
197 // actual definition for opaque type
198 struct __NSObjectFileImage
201 const void* imageBaseAddress
; // not used with OFI created from files
202 size_t imageLength
; // not used with OFI created from files
204 static std::vector
<NSObjectFileImage
> sObjectFileImages
;
209 // __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
210 // The contained image is delete in one of two places:
211 // NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
212 // NSDestroyObjectFileImage deletes the image if image is not in list of valid images
216 static void dyldAPIhalt(const char* apiName
, const char* errorMsg
)
218 fprintf(stderr
, "dyld: %s() error\n", apiName
);
219 dyld::halt(errorMsg
);
224 static void setLastError(NSLinkEditErrors code
, int errnum
, const char* file
, const char* message
)
226 dyld::setErrorMessage(message
);
227 strncpy(sLastErrorFilePath
, file
, 1024);
228 sLastErrorFilePath
[1023] = '\0';
229 sLastErrorFileCode
= code
;
230 sLastErrorNo
= errnum
;
235 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
236 * copies the path of the executable into the buffer and returns 0 if the path
237 * was successfully copied in the provided buffer. If the buffer is not large
238 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
239 * Note that _NSGetExecutablePath will return "a path" to the executable not a
240 * "real path" to the executable. That is the path may be a symbolic link and
241 * not the real file. And with deep directories the total bufsize needed could
242 * be more than MAXPATHLEN.
244 int _NSGetExecutablePath(char* buf
, uint32_t *bufsize
)
246 if ( dyld::gLogAPIs
)
247 fprintf(stderr
, "%s(...)\n", __func__
);
248 const char* exePath
= dyld::getExecutablePath();
249 if(*bufsize
< strlen(exePath
) + 1){
250 *bufsize
= strlen(exePath
) + 1;
253 strcpy(buf
, exePath
);
259 // _dyld_call_module_initializers_for_dylib() is the dyld side of
260 // __initialize_Cplusplus() which is in dylib1.o.
261 // It is intended to only be called inside -init rouintes.
262 // -init routines are called before module initializers (what C++
263 // initializers use). Calling __initialize_Cplusplus() in a -init
264 // routine causes the module initializers for an image to be called
265 // which then allows C++ to be used inside a -init routine
267 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
)
269 if ( dyld::gLogAPIs
)
270 fprintf(stderr
, "__initialize_Cplusplus()\n");
272 // for now, do nothing...
276 void _dyld_lookup_and_bind_fully(const char* symbolName
, void** address
, NSModule
* module)
278 if ( dyld::gLogAPIs
)
279 fprintf(stderr
, "%s(\"%s\", %p, %p)\n", __func__
, symbolName
, address
, module);
281 const ImageLoader::Symbol
* sym
;
282 dyld::clearErrorMessage();
283 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
285 dyld::link(image
, ImageLoader::kLazyOnly
, ImageLoader::kDontRunInitializers
);
286 if ( address
!= NULL
)
287 *address
= (void*)image
->getExportedSymbolAddress(sym
);
289 *module = ImageLoaderToNSModule(image
);
291 catch (const char* msg
) {
292 dyldAPIhalt(__func__
, msg
);
296 // on failure to find symbol return NULLs
297 if ( address
!= NULL
)
304 // Note: This cannot have public name because dyld is built with a static copy of libc.a
305 // which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
306 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module)
308 if ( dyld::gLogAPIs
)
309 fprintf(stderr
, "_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName
, address
, module);
311 const ImageLoader::Symbol
* sym
;
312 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
313 if ( address
!= NULL
)
314 *address
= (void*)image
->getExportedSymbolAddress(sym
);
316 *module = ImageLoaderToNSModule(image
);
319 // on failure to find symbol return NULLs
320 if ( address
!= NULL
)
327 void _dyld_lookup_and_bind_with_hint(const char* symbolName
, const char* library_name_hint
, void** address
, NSModule
* module)
329 if ( dyld::gLogAPIs
)
330 fprintf(stderr
, "%s(\"%s\", \"%s\", %p, %p)\n", __func__
, symbolName
, library_name_hint
, address
, module);
332 const ImageLoader::Symbol
* sym
;
333 // Look for library whose path contains the hint. If that fails search everywhere
334 if ( dyld::flatFindExportedSymbolWithHint(symbolName
, library_name_hint
, &sym
, &image
)
335 || dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
336 if ( address
!= NULL
)
337 *address
= (void*)image
->getExportedSymbolAddress(sym
);
339 *module = ImageLoaderToNSModule(image
);
342 // on failure to find symbol return NULLs
343 if ( address
!= NULL
)
351 NSSymbol
NSLookupAndBindSymbol(const char *symbolName
)
353 if ( dyld::gLogAPIs
)
354 fprintf(stderr
, "%s(\"%s\")\n", __func__
, symbolName
);
356 const ImageLoader::Symbol
* sym
;
357 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
358 return SymbolToNSSymbol(sym
);
360 // return NULL on failure
364 NSSymbol
NSLookupAndBindSymbolWithHint(const char* symbolName
, const char* libraryNameHint
)
366 if ( dyld::gLogAPIs
)
367 fprintf(stderr
, "%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
369 const ImageLoader::Symbol
* sym
;
370 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
372 // hint failed, do slow search of all images
373 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
376 return SymbolToNSSymbol(sym
);
378 // return NULL on failure and log
379 if ( dyld::gLogAPIs
)
380 fprintf(stderr
, "%s(\"%s\", \"%s\") => NULL \n", __func__
, symbolName
, libraryNameHint
);
384 uint32_t _dyld_image_count(void)
386 if ( dyld::gLogAPIs
)
387 fprintf(stderr
, "%s()\n", __func__
);
388 return dyld::getImageCount();
391 const struct mach_header
* _dyld_get_image_header(uint32_t image_index
)
393 if ( dyld::gLogAPIs
)
394 fprintf(stderr
, "%s(%u)\n", __func__
, image_index
);
395 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
397 return (struct mach_header
*)image
->machHeader();
403 static __attribute__((noinline
))
404 const struct mach_header
* addImage(const char* path
, bool search
, bool dontLoad
, bool matchInstallName
, bool abortOnError
)
406 ImageLoader
* image
= NULL
;
408 dyld::clearErrorMessage();
409 void* callerAddress
= __builtin_return_address(2); // note layers: 2: real client, 1: libSystem glue, 0: dyld API
410 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
411 dyld::LoadContext context
;
412 context
.useSearchPaths
= search
;
413 context
.useLdLibraryPath
= false;
414 context
.matchByInstallName
= matchInstallName
;
415 context
.dontLoad
= dontLoad
;
416 context
.mustBeBundle
= false;
417 context
.mustBeDylib
= true;
418 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
419 context
.rpath
= NULL
; // support not yet implemented
421 image
= load(path
, context
);
422 if ( image
!= NULL
) {
423 if ( context
.matchByInstallName
)
424 image
->setMatchInstallPath(true);
425 dyld::link(image
, ImageLoader::kNonLazyOnly
, ImageLoader::kRunInitializers
);
426 return image
->machHeader();
429 catch (const char* msg
) {
431 char pathMsg
[strlen(msg
)+strlen(path
)+4];
432 strcpy(pathMsg
, msg
);
433 strcat(pathMsg
, " ");
434 strcat(pathMsg
, path
);
435 dyldAPIhalt("NSAddImage", pathMsg
);
437 // not halting, so set error state for NSLinkEditError to find
438 setLastError(NSLinkEditOtherError
, 0, path
, msg
);
443 const struct mach_header
* NSAddImage(const char* path
, uint32_t options
)
445 if ( dyld::gLogAPIs
)
446 fprintf(stderr
, "%s(\"%s\", 0x%08X)\n", __func__
, path
, options
);
447 const bool dontLoad
= ( (options
& NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
) != 0 );
448 const bool search
= ( (options
& NSADDIMAGE_OPTION_WITH_SEARCHING
) != 0 );
449 const bool matchInstallName
= ( (options
& NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME
) != 0 );
450 const bool abortOnError
= ( (options
& NSADDIMAGE_OPTION_RETURN_ON_ERROR
) == 0 );
451 return addImage(path
, search
, dontLoad
, matchInstallName
, abortOnError
);
454 bool NSAddLibrary(const char* path
)
456 if ( dyld::gLogAPIs
)
457 fprintf(stderr
, "%s(\"%s\")\n", __func__
, path
);
458 return (addImage(path
, false, false, false, false) != NULL
);
461 bool NSAddLibraryWithSearching(const char* path
)
463 if ( dyld::gLogAPIs
)
464 fprintf(stderr
, "%s(\"%s\")\n", __func__
, path
);
465 return (addImage(path
, true, false, false, false) != NULL
);
470 //#define NSADDIMAGE_OPTION_NONE 0x0
471 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
472 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
474 bool NSIsSymbolNameDefinedInImage(const struct mach_header
* mh
, const char* symbolName
)
476 if ( dyld::gLogAPIs
)
477 fprintf(stderr
, "%s(%p, \"%s\")\n", __func__
, (void *)mh
, symbolName
);
478 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
479 if ( image
!= NULL
) {
480 if ( image
->findExportedSymbol(symbolName
, NULL
, true, NULL
) != NULL
)
486 NSSymbol
NSLookupSymbolInImage(const struct mach_header
* mh
, const char* symbolName
, uint32_t options
)
488 if ( dyld::gLogAPIs
)
489 fprintf(stderr
, "%s(%p, \"%s\", 0x%08X)\n", __func__
, mh
, symbolName
, options
);
490 const ImageLoader::Symbol
* symbol
= NULL
;
491 dyld::clearErrorMessage();
492 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
493 if ( image
!= NULL
) {
495 if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY
) {
496 dyld::link(image
, ImageLoader::kLazyOnly
, ImageLoader::kDontRunInitializers
);
498 else if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
) {
499 dyld::link(image
, ImageLoader::kLazyOnlyNoDependents
, ImageLoader::kDontRunInitializers
);
502 catch (const char* msg
) {
503 if ( (options
& NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
) == 0 ) {
504 dyldAPIhalt(__func__
, msg
);
507 symbol
= image
->findExportedSymbol(symbolName
, NULL
, true, NULL
);
509 if ( dyld::gLogAPIs
&& (symbol
== NULL
) )
510 fprintf(stderr
, "%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__
, mh
, symbolName
, options
);
511 return SymbolToNSSymbol(symbol
);
515 // Note: This cannot have public name because dyld is built with a static copy of libc.a
516 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
517 static bool client_NSIsSymbolNameDefined(const char* symbolName
)
519 if ( dyld::gLogAPIs
)
520 fprintf(stderr
, "NSIsSymbolNameDefined(\"%s\")\n", symbolName
);
522 const ImageLoader::Symbol
* sym
;
523 return dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
526 bool NSIsSymbolNameDefinedWithHint(const char* symbolName
, const char* libraryNameHint
)
528 if ( dyld::gLogAPIs
)
529 fprintf(stderr
, "%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
531 const ImageLoader::Symbol
* sym
;
532 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
534 // hint failed, do slow search of all images
535 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
537 if ( !found
&& dyld::gLogAPIs
)
538 fprintf(stderr
, "%s(\"%s\", \"%s\") => false \n", __func__
, symbolName
, libraryNameHint
);
542 const char* NSNameOfSymbol(NSSymbol symbol
)
544 if ( dyld::gLogAPIs
)
545 fprintf(stderr
, "%s(%p)\n", __func__
, (void *)symbol
);
546 const char* result
= NULL
;
547 ImageLoader
* image
= dyld::findImageContainingAddress(symbol
);
549 result
= image
->getExportedSymbolName(NSSymbolToSymbol(symbol
));
553 void* NSAddressOfSymbol(NSSymbol symbol
)
555 if ( dyld::gLogAPIs
)
556 fprintf(stderr
, "%s(%p)\n", __func__
, (void *)symbol
);
558 ImageLoader
* image
= dyld::findImageContainingAddress(symbol
);
560 result
= (void*)image
->getExportedSymbolAddress(NSSymbolToSymbol(symbol
));
564 NSModule
NSModuleForSymbol(NSSymbol symbol
)
566 if ( dyld::gLogAPIs
)
567 fprintf(stderr
, "%s(%p)\n", __func__
, (void *)symbol
);
568 NSModule result
= NULL
;
569 ImageLoader
* image
= dyld::findImageContainingAddress(symbol
);
571 result
= ImageLoaderToNSModule(image
);
576 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index
)
578 if ( dyld::gLogAPIs
)
579 fprintf(stderr
, "%s(%u)\n", __func__
, image_index
);
580 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
582 return image
->getSlide();
587 const char* _dyld_get_image_name(uint32_t image_index
)
589 if ( dyld::gLogAPIs
)
590 fprintf(stderr
, "%s(%u)\n", __func__
, image_index
);
591 ImageLoader
* image
= dyld::getIndexedImage(image_index
);
593 return image
->getLogicalPath();
600 bool _dyld_all_twolevel_modules_prebound(void)
602 if ( dyld::gLogAPIs
)
603 fprintf(stderr
, "%s()\n", __func__
);
604 return FALSE
; // fixme
607 void _dyld_bind_objc_module(const void *objc_module
)
609 if ( dyld::gLogAPIs
)
610 fprintf(stderr
, "%s(%p)\n", __func__
, objc_module
);
611 // do nothing, with new dyld everything already bound
615 bool _dyld_bind_fully_image_containing_address(const void* address
)
617 if ( dyld::gLogAPIs
)
618 fprintf(stderr
, "%s(%p)\n", __func__
, address
);
619 dyld::clearErrorMessage();
620 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
621 if ( image
!= NULL
) {
623 dyld::link(image
, ImageLoader::kLazyAndNonLazy
, ImageLoader::kDontRunInitializers
);
626 catch (const char* msg
) {
627 dyldAPIhalt(__func__
, msg
);
633 bool _dyld_image_containing_address(const void* address
)
635 if ( dyld::gLogAPIs
)
636 fprintf(stderr
, "%s(%p)\n", __func__
, address
);
637 ImageLoader
*imageLoader
= dyld::findImageContainingAddress(address
);
638 return (NULL
!= imageLoader
);
641 static NSObjectFileImage
createObjectImageFile(ImageLoader
* image
, const void* address
= NULL
, size_t len
=0)
643 NSObjectFileImage result
= new __NSObjectFileImage();
644 result
->image
= image
;
645 result
->imageBaseAddress
= address
;
646 result
->imageLength
= len
;
647 sObjectFileImages
.push_back(result
);
651 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* pathName
, NSObjectFileImage
*objectFileImage
)
653 if ( dyld::gLogAPIs
)
654 fprintf(stderr
, "%s(\"%s\", ...)\n", __func__
, pathName
);
656 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
657 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
659 dyld::LoadContext context
;
660 context
.useSearchPaths
= false;
661 context
.useLdLibraryPath
= false;
662 context
.matchByInstallName
= false;
663 context
.dontLoad
= false;
664 context
.mustBeBundle
= true;
665 context
.mustBeDylib
= false;
666 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
667 context
.rpath
= NULL
; // support not yet implemented
669 ImageLoader
* image
= dyld::load(pathName
, context
);
670 // Note: We DO NOT link the image! NSLinkModule will do that
671 if ( image
!= NULL
) {
672 if ( !image
->isBundle() ) {
673 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
674 return NSObjectFileImageInappropriateFile
;
676 *objectFileImage
= createObjectImageFile(image
);
677 return NSObjectFileImageSuccess
;
680 catch (const char* msg
) {
681 //fprintf(stderr, "dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
682 return NSObjectFileImageInappropriateFile
;
684 return NSObjectFileImageFailure
;
688 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* address
, size_t size
, NSObjectFileImage
*objectFileImage
)
690 if ( dyld::gLogAPIs
)
691 fprintf(stderr
, "%s(%p, %lu, %p)\n", __func__
, address
, size
, objectFileImage
);
694 ImageLoader
* image
= dyld::loadFromMemory((const uint8_t*)address
, size
, NULL
);
695 if ( ! image
->isBundle() ) {
696 // this API can only be used with bundles...
698 return NSObjectFileImageInappropriateFile
;
700 // Note: We DO NOT link the image! NSLinkModule will do that
701 if ( image
!= NULL
) {
702 *objectFileImage
= createObjectImageFile(image
, address
, size
);
703 return NSObjectFileImageSuccess
;
706 catch (const char* msg
) {
707 fprintf(stderr
, "dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg
);
709 return NSObjectFileImageFailure
;
712 static bool validOFI(NSObjectFileImage objectFileImage
)
714 const int ofiCount
= sObjectFileImages
.size();
715 for (int i
=0; i
< ofiCount
; ++i
) {
716 if ( sObjectFileImages
[i
] == objectFileImage
)
722 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage
)
724 if ( dyld::gLogAPIs
)
725 fprintf(stderr
, "%s(%p)\n", __func__
, objectFileImage
);
727 if ( validOFI(objectFileImage
) ) {
728 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
729 // and we should delete it
730 bool linkedImage
= dyld::validImage(objectFileImage
->image
);
732 delete objectFileImage
->image
;
734 // remove from list of ofi's
735 for (std::vector
<NSObjectFileImage
>::iterator it
=sObjectFileImages
.begin(); it
!= sObjectFileImages
.end(); it
++) {
736 if ( *it
== objectFileImage
) {
737 sObjectFileImages
.erase(it
);
742 // if object was created from a memory, release that memory
743 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
744 if ( objectFileImage
->imageBaseAddress
!= NULL
) {
745 vm_deallocate(mach_task_self(), (vm_address_t
)objectFileImage
->imageBaseAddress
, objectFileImage
->imageLength
);
749 delete objectFileImage
;
756 bool NSHasModInitObjectFileImage(NSObjectFileImage objectFileImage
)
758 if ( dyld::gLogAPIs
)
759 fprintf(stderr
, "%s(%p)\n", __func__
, objectFileImage
);
760 return objectFileImage
->image
->needsInitialization();
763 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
765 if ( dyld::gLogAPIs
)
766 fprintf(stderr
, "%s(%p)\n", __func__
, objectFileImage
);
767 return objectFileImage
->image
->getExportedSymbolCount();
770 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
772 if ( dyld::gLogAPIs
)
773 fprintf(stderr
, "%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
774 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedExportedSymbol(ordinal
);
775 return objectFileImage
->image
->getExportedSymbolName(sym
);
778 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
780 if ( dyld::gLogAPIs
)
781 fprintf(stderr
, "%s(%p)\n", __func__
, objectFileImage
);
782 return objectFileImage
->image
->getImportedSymbolCount();
785 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
,
786 bool* tentative_definition
)
788 if ( dyld::gLogAPIs
)
789 fprintf(stderr
, "%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
790 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedImportedSymbol(ordinal
);
791 if ( tentative_definition
!= NULL
) {
792 ImageLoader::ReferenceFlags flags
= objectFileImage
->image
->geImportedSymbolInfo(sym
);
793 if ( (flags
& ImageLoader::kTentativeDefinition
) != 0 )
794 *tentative_definition
= true;
796 *tentative_definition
= false;
798 return objectFileImage
->image
->getImportedSymbolName(sym
);
801 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage
,
802 const char* segmentName
, const char* sectionName
, unsigned long* size
)
804 if ( dyld::gLogAPIs
)
805 fprintf(stderr
, "%s(%p,%s, %s)\n", __func__
, objectFileImage
, segmentName
, sectionName
);
809 if ( objectFileImage
->image
->getSectionContent(segmentName
, sectionName
, &start
, &length
) ) {
819 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage
, const char* symbolName
)
821 if ( dyld::gLogAPIs
)
822 fprintf(stderr
, "%s(%p,%s)\n", __func__
, objectFileImage
, symbolName
);
823 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->findExportedSymbol(symbolName
, NULL
, true, NULL
);
824 return ( sym
!= NULL
);
828 * Given an imageOffset into an ObjectFileImage, returns
829 * the segment/section name and offset into that section of
830 * that imageOffset. Returns FALSE if the imageOffset is not
831 * in any section. You can used the resulting sectionOffset to
832 * index into the data returned by NSGetSectionDataInObjectFileImage.
834 * First appeared in Mac OS X 10.3
836 * SPI: currently only used by ZeroLink to detect +load methods
839 NSFindSectionAndOffsetInObjectFileImage(NSObjectFileImage objectFileImage
,
840 unsigned long imageOffset
,
841 const char** segmentName
, /* can be NULL */
842 const char** sectionName
, /* can be NULL */
843 unsigned long* sectionOffset
) /* can be NULL */
845 if ( dyld::gLogAPIs
)
846 fprintf(stderr
, "%s(%p)\n", __func__
, objectFileImage
);
848 return objectFileImage
->image
->findSection((char*)(objectFileImage
->image
->getBaseAddress())+imageOffset
, segmentName
, sectionName
, sectionOffset
);
853 NSModule
NSLinkModule(NSObjectFileImage objectFileImage
, const char* moduleName
, uint32_t options
)
855 if ( dyld::gLogAPIs
)
856 fprintf(stderr
, "%s(%p, \"%s\", 0x%08X)\n", __func__
, objectFileImage
, moduleName
, options
);
858 dyld::clearErrorMessage();
860 // NSLinkModule allows a bundle to be link multpile times
861 // each link causes the bundle to be copied to a new address
862 if ( objectFileImage
->image
->isLinked() ) {
863 // already linked, so clone a new one and link it
865 fprintf(stderr
, "dyld: warning: %s(0x%08X, \"%s\", 0x%08X) called more than once for 0x%08X\n",
866 __func__
, objectFileImage
, moduleName
, options
, objectFileImage
);
868 objectFileImage
->image
= dyld::cloneImage(objectFileImage
->image
);
871 // if this ofi was made with NSCreateObjectFileImageFromFile() then physical path is already set
872 // if this ofi was create with NSCreateObjectFileImageFromMemory() then the phyiscal path should be set if supplied
873 if ( (options
& NSLINKMODULE_OPTION_TRAILING_PHYS_NAME
) != 0 ) {
874 if ( objectFileImage
->imageBaseAddress
!= NULL
) {
875 const char* physEnd
= &moduleName
[strlen(moduleName
)+1];
876 objectFileImage
->image
->setPath(physEnd
);
880 // set moduleName as the name anyone calling _dyld_get_image_name() will see
881 objectFileImage
->image
->setLogicalPath(moduleName
);
883 // support private bundles
884 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
885 objectFileImage
->image
->setHideExports();
887 // set up linking options
888 ImageLoader::BindingLaziness bindness
= ImageLoader::kNonLazyOnly
;
889 if ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 )
890 bindness
= ImageLoader::kLazyAndNonLazy
;
891 ImageLoader::InitializerRunning runInitializers
= ImageLoader::kRunInitializers
;
892 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) != 0 )
893 runInitializers
= ImageLoader::kDontRunInitializersButTellObjc
;
895 // load libraries, rebase, bind, to make this image usable
896 dyld::link(objectFileImage
->image
, bindness
, runInitializers
);
898 return ImageLoaderToNSModule(objectFileImage
->image
);
900 catch (const char* msg
) {
901 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
902 dyldAPIhalt(__func__
, msg
);
903 // not halting, so set error state for NSLinkEditError to find
904 dyld::removeImage(objectFileImage
->image
);
905 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
910 #if OLD_LIBSYSTEM_SUPPORT
911 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
912 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
)
914 if ( dyld::gLogAPIs
)
915 fprintf(stderr
, "%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr
, moduleName
, options
); // note name/args translation
916 ImageLoader
* image
= NULL
;
917 dyld::clearErrorMessage();
919 const char* imageName
= moduleName
;
920 if ( (options
& NSLINKMODULE_OPTION_TRAILING_PHYS_NAME
) != 0 )
921 imageName
= &moduleName
[strlen(moduleName
)+1];
923 image
= dyld::loadFromMemory((const uint8_t*)object_addr
, object_size
, imageName
);
925 if ( (options
& NSLINKMODULE_OPTION_TRAILING_PHYS_NAME
) != 0 )
926 image
->setLogicalPath(moduleName
);
928 if ( image
!= NULL
) {
929 // support private bundles
930 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
931 image
->setHideExports();
933 // set up linking options
934 ImageLoader::BindingLaziness bindness
= ImageLoader::kNonLazyOnly
;
935 if ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 )
936 bindness
= ImageLoader::kLazyAndNonLazy
;
937 ImageLoader::InitializerRunning runInitializers
= ImageLoader::kRunInitializers
;
938 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) != 0 )
939 runInitializers
= ImageLoader::kDontRunInitializersButTellObjc
;
941 // load libraries, rebase, bind, to make this image usable
942 dyld::link(image
, bindness
, runInitializers
);
945 catch (const char* msg
) {
946 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
947 dyldAPIhalt("NSLinkModule", msg
);
948 // not halting, so set error state for NSLinkEditError to find
949 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
950 // if image was created for this bundle, destroy it
951 if ( image
!= NULL
) {
952 dyld::removeImage(image
);
957 return ImageLoaderToNSModule(image
);
961 NSSymbol
NSLookupSymbolInModule(NSModule
module, const char* symbolName
)
963 if ( dyld::gLogAPIs
)
964 fprintf(stderr
, "%s(%p, \"%s\")\n", __func__
, (void *)module, symbolName
);
965 ImageLoader
* image
= NSModuleToImageLoader(module);
968 return SymbolToNSSymbol(image
->findExportedSymbol(symbolName
, NULL
, false, NULL
));
971 const char* NSNameOfModule(NSModule
module)
973 if ( dyld::gLogAPIs
)
974 fprintf(stderr
, "%s(%p)\n", __func__
, module);
975 ImageLoader
* image
= NSModuleToImageLoader(module);
978 return image
->getPath();
981 const char* NSLibraryNameForModule(NSModule
module)
983 if ( dyld::gLogAPIs
)
984 fprintf(stderr
, "%s(%p)\n", __func__
, module);
985 ImageLoader
* image
= NSModuleToImageLoader(module);
988 return image
->getPath();
991 bool NSUnLinkModule(NSModule
module, uint32_t options
)
993 if ( dyld::gLogAPIs
)
994 fprintf(stderr
, "%s(%p, 0x%08X)\n", __func__
, module, options
);
995 if ( module == NULL
)
997 ImageLoader
* image
= NSModuleToImageLoader(module);
1000 dyld::removeImage(image
);
1002 if ( (options
& NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
) != 0 )
1003 image
->setLeaveMapped();
1005 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1007 // Only delete image if there is no ofi referencing it
1008 // That means the ofi was destroyed after linking, so no one is left to delete this image
1009 const int ofiCount
= sObjectFileImages
.size();
1011 for (int i
=0; i
< ofiCount
; ++i
) {
1012 NSObjectFileImage ofi
= sObjectFileImages
[i
];
1013 if ( ofi
->image
== image
)
1022 // internal name and parameters do not match public name and parameters...
1023 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
)
1025 if ( dyld::gLogAPIs
)
1026 fprintf(stderr
, "NSLinkEditErrorHandlers()\n");
1028 dyld::registerUndefinedHandler((dyld::UndefinedHandler
)undefined
);
1029 // no support for multiple or linkedit handlers
1032 const struct mach_header
* _dyld_get_image_header_containing_address(const void* address
)
1034 if ( dyld::gLogAPIs
)
1035 fprintf(stderr
, "%s(%p)\n", __func__
, address
);
1036 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1037 if ( image
!= NULL
)
1038 return image
->machHeader();
1043 void _dyld_register_func_for_add_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
1045 if ( dyld::gLogAPIs
)
1046 fprintf(stderr
, "%s(%p)\n", __func__
, (void *)func
);
1047 dyld::registerAddCallback(func
);
1050 void _dyld_register_func_for_remove_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
1052 if ( dyld::gLogAPIs
)
1053 fprintf(stderr
, "%s(%p)\n", __func__
, (void *)func
);
1054 dyld::registerRemoveCallback(func
);
1057 // called by atexit() function installed by crt
1058 static void _dyld_mod_term_funcs()
1060 if ( dyld::gLogAPIs
)
1061 fprintf(stderr
, "%s()\n", __func__
);
1062 dyld::runTerminators();
1065 // called by crt before main
1066 static void _dyld_make_delayed_module_initializer_calls()
1068 if ( dyld::gLogAPIs
)
1069 fprintf(stderr
, "%s()\n", __func__
);
1070 dyld::initializeMainExecutable();
1074 void NSLinkEditError(NSLinkEditErrors
* c
, int* errorNumber
, const char** fileName
, const char** errorString
)
1077 *c
= sLastErrorFileCode
;
1078 *errorNumber
= sLastErrorNo
;
1079 *fileName
= sLastErrorFilePath
;
1080 *errorString
= dyld::getErrorMessage();
1083 static void _dyld_register_binding_handler(void * (*bindingHandler
)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions
)
1085 if ( dyld::gLogAPIs
)
1086 fprintf(stderr
, "%s()\n", __func__
);
1087 dyld::gLinkContext
.bindingHandler
= bindingHandler
;
1088 dyld::gLinkContext
.bindingOptions
= bindingOptions
;
1091 // Call by fork() in libSystem before the kernel trap is done
1092 static void _dyld_fork_prepare()
1094 if ( dyld::gLogAPIs
)
1095 fprintf(stderr
, "%s()\n", __func__
);
1098 // Call by fork() in libSystem after the kernel trap is done on the parent side
1099 static void _dyld_fork_parent()
1101 if ( dyld::gLogAPIs
)
1102 fprintf(stderr
, "%s()\n", __func__
);
1105 // Call by fork() in libSystem after the kernel trap is done on the child side
1106 static void _dyld_fork_child()
1108 if ( dyld::gLogAPIs
)
1109 fprintf(stderr
, "%s()\n", __func__
);
1110 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1111 // in libSystem for the child of a fork. But dyld is built with a static copy
1112 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1114 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1115 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1117 extern mach_port_t mach_task_self_
;
1118 mach_task_self_
= task_self_trap();
1121 // Call by fork() in libSystem after the kernel trap is done on the child side after
1122 // other libSystem child side fixups are done
1123 static void _dyld_fork_child_final()
1125 if ( dyld::gLogAPIs
)
1126 fprintf(stderr
, "%s()\n", __func__
);
1130 typedef void (*MonitorProc
)(char *lowpc
, char *highpc
);
1132 static void monInitCallback(ImageLoader
* image
, void* userData
)
1134 MonitorProc proc
= (MonitorProc
)userData
;
1137 if ( image
->getSectionContent("__TEXT", "__text", &start
, &length
) ) {
1138 proc((char*)start
, (char*)start
+length
);
1143 // _dyld_moninit is called from profiling runtime routine moninit().
1144 // dyld calls back with the range of each __TEXT/__text section in every
1147 void _dyld_moninit(MonitorProc proc
)
1149 dyld::forEachImageDo(&monInitCallback
, (void*)proc
);
1152 // returns true if prebinding was used in main executable
1153 bool _dyld_launched_prebound()
1155 if ( dyld::gLogAPIs
)
1156 fprintf(stderr
, "%s()\n", __func__
);
1158 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1159 return dyld::mainExecutablePrebound();
1164 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1165 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1166 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1167 // flag on the image for this module. If the module was found and it was
1168 // private then everything worked and TRUE is returned else FALSE is returned.
1170 static bool NSMakePrivateModulePublic(NSModule
module)
1172 ImageLoader
* image
= NSModuleToImageLoader(module);
1173 if ( image
!= NULL
) {
1174 if ( image
->hasHiddenExports() ) {
1175 image
->setHideExports(false);
1184 bool lookupDyldFunction(const char* name
, uintptr_t* address
)
1186 for (const dyld_func
* p
= dyld_funcs
; p
->name
!= NULL
; ++p
) {
1187 if ( strcmp(p
->name
, name
) == 0 ) {
1188 if( p
->implementation
== unimplemented
)
1189 fprintf(stderr
, "unimplemented dyld function: %s\n", p
->name
);
1190 *address
= (uintptr_t)p
->implementation
;
1199 static void registerThreadHelpers(const dyld::ThreadingHelpers
* helpers
)
1201 // We need to make sure libSystem's lazy pointer's are bound
1202 // before installing thred helpers.
1203 // The reason for this is that if accessing the lock requires
1204 // a lazy pointer to be bound (and it does when multi-module
1205 // libSystem) is not prebound, the lazy handler will be
1206 // invoked which tries to acquire the lock again...an infinite
1208 ImageLoader
* image
= dyld::findImageContainingAddress(helpers
);
1209 dyld::link(image
, ImageLoader::kLazyOnly
, ImageLoader::kDontRunInitializers
);
1211 dyld::gThreadHelpers
= helpers
;
1215 static void dlerrorClear()
1217 if ( dyld::gThreadHelpers
!= NULL
) {
1218 char* buffer
= (*dyld::gThreadHelpers
->getThreadBufferFor_dlerror
)(1);
1223 static void dlerrorSet(const char* msg
)
1225 if ( dyld::gThreadHelpers
!= NULL
) {
1226 char* buffer
= (*dyld::gThreadHelpers
->getThreadBufferFor_dlerror
)(strlen(msg
)+1);
1227 strcpy(buffer
, msg
);
1233 void* dlopen(const char* path
, int mode
)
1235 if ( dyld::gLogAPIs
)
1236 fprintf(stderr
, "%s(%s, 0x%08X)\n", __func__
, path
, mode
);
1240 // passing NULL for path means return magic object
1241 if ( path
== NULL
) {
1242 return RTLD_DEFAULT
;
1246 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1247 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1249 ImageLoader
* image
= NULL
;
1250 dyld::LoadContext context
;
1251 context
.useSearchPaths
= true;
1252 context
.useLdLibraryPath
= (strchr(path
, '/') == NULL
); // a leafname implies should search
1253 context
.matchByInstallName
= true;
1254 context
.dontLoad
= ( (mode
& RTLD_NOLOAD
) != 0 );
1255 context
.mustBeBundle
= false;
1256 context
.mustBeDylib
= false;
1257 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1258 context
.rpath
= NULL
; // support not yet implemented
1260 image
= load(path
, context
);
1261 if ( image
!= NULL
) {
1262 image
->incrementReferenceCount();
1263 if ( ! image
->isLinked() ) {
1264 ImageLoader::BindingLaziness bindiness
= ImageLoader::kNonLazyOnly
;
1265 if ( (mode
& RTLD_NOW
) != 0 )
1266 bindiness
= ImageLoader::kLazyAndNonLazy
;
1267 dyld::link(image
, bindiness
, ImageLoader::kRunInitializers
);
1268 // only hide exports if image is not already in use
1269 if ( (mode
& RTLD_LOCAL
) != 0 )
1270 image
->setHideExports(true);
1272 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1273 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1274 // The subtle differences are:
1275 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1276 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1277 if ( (mode
& RTLD_NODELETE
) != 0 )
1278 image
->setLeaveMapped();
1282 catch (const char* msg
) {
1283 const char* format
= "dlopen(%s, %d): %s";
1284 char temp
[strlen(format
)+strlen(path
)+strlen(msg
)+10];
1285 sprintf(temp
, format
, path
, mode
, msg
);
1291 int dlclose(void* handle
)
1293 if ( dyld::gLogAPIs
)
1294 fprintf(stderr
, "%s(%p)\n", __func__
, handle
);
1296 ImageLoader
* image
= (ImageLoader
*)handle
;
1297 if ( dyld::validImage(image
) ) {
1298 if ( image
->decrementReferenceCount() ) {
1299 // for now, only bundles can be unloaded
1300 // to unload dylibs we would need to track all direct and indirect uses
1301 if ( image
->isBundle() ) {
1302 dyld::removeImage(image
);
1310 dlerrorSet("invalid handle passed to dlclose()");
1317 int dladdr(const void* address
, Dl_info
* info
)
1319 if ( dyld::gLogAPIs
)
1320 fprintf(stderr
, "%s(%p, %p)\n", __func__
, address
, info
);
1322 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1323 if ( image
!= NULL
) {
1324 info
->dli_fname
= image
->getLogicalPath();
1325 info
->dli_fbase
= (void*)image
->machHeader();
1326 // find closest exported symbol in the image
1327 const uint32_t exportCount
= image
->getExportedSymbolCount();
1328 const ImageLoader::Symbol
* bestSym
= NULL
;
1329 const void* bestAddr
= 0;
1330 for(uint32_t i
=0; i
< exportCount
; ++i
) {
1331 const ImageLoader::Symbol
* sym
= image
->getIndexedExportedSymbol(i
);
1332 const void* symAddr
= (void*)image
->getExportedSymbolAddress(sym
);
1333 if ( (symAddr
<= address
) && (bestAddr
< symAddr
) ) {
1338 if ( bestSym
!= NULL
) {
1339 info
->dli_sname
= image
->getExportedSymbolName(bestSym
) + 1; // strip off leading underscore
1340 info
->dli_saddr
= (void*)bestAddr
;
1343 info
->dli_sname
= NULL
;
1344 info
->dli_saddr
= NULL
;
1346 return 1; // success
1348 return 0; // failure
1354 if ( dyld::gLogAPIs
)
1355 fprintf(stderr
, "%s()\n", __func__
);
1357 if ( dyld::gThreadHelpers
!= NULL
) {
1358 char* buffer
= (*dyld::gThreadHelpers
->getThreadBufferFor_dlerror
)(1);
1359 // if no error set, return NULL
1360 if ( buffer
[0] != '\0' )
1366 void* dlsym(void* handle
, const char* symbolName
)
1368 if ( dyld::gLogAPIs
)
1369 fprintf(stderr
, "%s(%p, %s)\n", __func__
, handle
, symbolName
);
1374 const ImageLoader::Symbol
* sym
;
1376 // dlsym() assumes symbolName passed in is same as in C source code
1377 // dyld assumes all symbol names have an underscore prefix
1378 char underscoredName
[strlen(symbolName
)+2];
1379 underscoredName
[0] = '_';
1380 strcpy(&underscoredName
[1], symbolName
);
1382 // magic "search all" handle
1383 if ( handle
== RTLD_DEFAULT
) {
1384 if ( dyld::flatFindExportedSymbol(underscoredName
, &sym
, &image
) ) {
1385 return (void*)image
->getExportedSymbolAddress(sym
);
1387 const char* format
= "dlsym(RTLD_DEFAULT, %s): symbol not found";
1388 char temp
[strlen(format
)+strlen(symbolName
)+2];
1389 sprintf(temp
, format
, symbolName
);
1394 // magic "search what I would see" handle
1395 if ( handle
== RTLD_NEXT
) {
1396 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1397 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1398 sym
= callerImage
->findExportedSymbolInDependentImages(underscoredName
, &image
); // don't search image, but do search what it links against
1399 if ( sym
!= NULL
) {
1400 return (void*)image
->getExportedSymbolAddress(sym
);
1402 const char* format
= "dlsym(RTLD_NEXT, %s): symbol not found";
1403 char temp
[strlen(format
)+strlen(symbolName
)+2];
1404 sprintf(temp
, format
, symbolName
);
1409 // magic "search me, then what I would see" handle
1410 if ( handle
== RTLD_SELF
) {
1411 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1412 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1413 sym
= callerImage
->findExportedSymbolInImageOrDependentImages(underscoredName
, &image
); // search image and what it links against
1414 if ( sym
!= NULL
) {
1415 return (void*)image
->getExportedSymbolAddress(sym
);
1417 const char* format
= "dlsym(RTLD_SELF, %s): symbol not found";
1418 char temp
[strlen(format
)+strlen(symbolName
)+2];
1419 sprintf(temp
, format
, symbolName
);
1425 image
= (ImageLoader
*)handle
;
1426 if ( dyld::validImage(image
) ) {
1427 sym
= image
->findExportedSymbolInImageOrDependentImages(underscoredName
, &image
); // search image and what it links against
1428 if ( sym
!= NULL
) {
1429 return (void*)image
->getExportedSymbolAddress(sym
);
1431 const char* format
= "dlsym(%p, %s): symbol not found";
1432 char temp
[strlen(format
)+strlen(symbolName
)+20];
1433 sprintf(temp
, format
, handle
, symbolName
);
1437 dlerrorSet("invalid handle passed to dlsym()");
1443 static void commitRepreboundFiles(std::vector
<ImageLoader
*> files
, bool unmapOld
)
1445 // tell file system to flush all dirty buffers to disk
1446 // after this sync, the _redoprebinding files will be on disk
1449 // now commit (swap file) for each re-prebound image
1450 // this only updates directories, since the files have already been flushed by previous sync()
1451 for (std::vector
<ImageLoader
*>::iterator it
=files
.begin(); it
!= files
.end(); it
++) {
1452 (*it
)->reprebindCommit(dyld::gLinkContext
, true, unmapOld
);
1455 // tell file system to flush all dirty buffers to disk
1456 // this should flush out all directory changes caused by the file swapping
1461 #define UPDATE_PREBINDING_DRY_RUN 0x00000001
1462 #define UPDATE_PREBINDING_PROGRESS 0x00000002
1465 // SPI called only by update_prebinding tool to redo prebinding in all prebound files specified
1466 // There must be no dylibs loaded when this fnction is called.
1468 __attribute__((noreturn
))
1469 static void _dyld_update_prebinding(int pathCount
, const char* paths
[], uint32_t flags
)
1471 if ( dyld::gLogAPIs
)
1472 fprintf(stderr
, "%s()\n", __func__
);
1474 // list of requested dylibs actually loaded
1475 std::vector
<ImageLoader
*> preboundImages
;
1478 // verify no dylibs loaded
1479 if ( dyld::getImageCount() != 1 )
1480 throw "_dyld_update_prebinding cannot be called with dylib already loaded";
1482 const uint32_t max_allowed_link_errors
= 10;
1483 uint32_t link_error_count
= 0;
1485 // load and link each dylib
1486 for (int i
=0; i
< pathCount
; ++i
) {
1487 dyld::LoadContext context
;
1488 context
.useSearchPaths
= false;
1489 context
.matchByInstallName
= true;
1490 context
.dontLoad
= false;
1491 context
.mustBeBundle
= false;
1492 context
.mustBeDylib
= true;
1493 context
.origin
= NULL
; // @loader_path not allowed in prebinding list
1494 context
.rpath
= NULL
; // support not yet implemented
1496 ImageLoader
* image
= NULL
;
1498 image
= dyld::load(paths
[i
], context
);
1499 // bind lazy and non-lazy symbols, but don't run initializers
1500 // this may bring in other dylibs later in the list or missing from list, but that is ok
1501 dyld::link(image
, ImageLoader::kLazyAndNonLazy
, ImageLoader::kDontRunInitializers
);
1502 // recored images we successfully loaded
1503 preboundImages
.push_back(image
);
1505 catch (const char* msg
) {
1506 if ( dyld::gLinkContext
.verbosePrebinding
|| (UPDATE_PREBINDING_DRY_RUN
& flags
) ) {
1508 if ( image
== NULL
) // load exception
1510 else // link exception
1512 fprintf(stderr
, "update_prebinding: warning: could not %s %s: %s\n", stage
, paths
[i
], msg
);
1514 if ( image
!= NULL
)
1516 if ( link_error_count
> max_allowed_link_errors
)
1521 // find missing images
1522 uint32_t loadedImageCount
= dyld::getImageCount();
1523 if ( loadedImageCount
> (preboundImages
.size()+1) ) {
1524 if ( dyld::gLinkContext
.verbosePrebinding
|| (UPDATE_PREBINDING_DRY_RUN
& flags
) )
1525 fprintf(stderr
, "update_prebinding: warning: the following dylibs were loaded but will not have their prebinding updated because they are not in the list of paths to reprebind\n");
1526 for (uint32_t i
=1; i
< loadedImageCount
; ++i
) {
1527 ImageLoader
* target
= dyld::getIndexedImage(i
);
1529 for (std::vector
<ImageLoader
*>::iterator it
=preboundImages
.begin(); it
!= preboundImages
.end(); it
++) {
1530 if ( *it
== target
) {
1536 if ( dyld::gLinkContext
.verbosePrebinding
|| (UPDATE_PREBINDING_DRY_RUN
& flags
) )
1537 fprintf(stderr
, " %s\n", target
->getPath());
1541 // warn about unprebound files in the list
1542 bool unpreboundWarned
= false;
1543 for (std::vector
<ImageLoader
*>::iterator it
=preboundImages
.begin(); it
!= preboundImages
.end(); it
++) {
1544 if ( ! (*it
)->isPrebindable() && (*it
!= dyld::mainExecutable()) ) {
1545 if ( ! unpreboundWarned
) {
1546 if ( dyld::gLinkContext
.verbosePrebinding
|| (UPDATE_PREBINDING_DRY_RUN
& flags
) )
1547 fprintf(stderr
, "update_prebinding: warning: the following dylibs were specified but were not built prebound\n");
1548 unpreboundWarned
= true;
1550 if ( dyld::gLinkContext
.verbosePrebinding
|| (UPDATE_PREBINDING_DRY_RUN
& flags
) )
1551 fprintf(stderr
, " %s\n", (*it
)->getPath());
1555 if(UPDATE_PREBINDING_DRY_RUN
& flags
) {
1556 fprintf(stderr
, "update_prebinding: dry-run: no changes were made to the filesystem.\n");
1559 uint32_t imageCount
= preboundImages
.size();
1560 uint32_t imageNumber
= 1;
1562 // on Intel system, update_prebinding is run twice: i386, then emulated ppc
1563 // calculate fudge factors so that progress output represents both runs
1564 int denomFactor
= 1;
1565 int numerAddend
= 0;
1566 if (UPDATE_PREBINDING_PROGRESS
& flags
) {
1568 // i386 half runs first, just double denominator
1572 // if emulated ppc, double denominator and shift numerator
1573 int mib
[] = { CTL_KERN
, KERN_CLASSIC
, getpid() };
1574 int is_emulated
= 0;
1575 size_t len
= sizeof(int);
1576 int ret
= sysctl(mib
, 3, &is_emulated
, &len
, NULL
, 0);
1577 if ((ret
!= -1) && is_emulated
) {
1579 numerAddend
= imageCount
;
1584 // tell each image to write itself out re-prebound
1585 struct timeval currentTime
= { 0 , 0 };
1586 gettimeofday(¤tTime
, NULL
);
1587 time_t timestamp
= currentTime
.tv_sec
;
1588 std::vector
<ImageLoader
*> updatedImages
;
1589 for (std::vector
<ImageLoader
*>::iterator it
=preboundImages
.begin(); it
!= preboundImages
.end(); it
++) {
1590 uint64_t freespace
= (*it
)->reprebind(dyld::gLinkContext
, timestamp
);
1591 updatedImages
.push_back(*it
);
1592 if(UPDATE_PREBINDING_PROGRESS
& flags
) {
1593 fprintf(stdout
, "update_prebinding: progress: %3u/%u\n", imageNumber
+numerAddend
, imageCount
*denomFactor
);
1597 // see if we are running low on disk space (less than 32MB is "low")
1598 const uint64_t kMinFreeSpace
= 32*1024*1024;
1599 if ( freespace
< kMinFreeSpace
) {
1600 if ( dyld::gLinkContext
.verbosePrebinding
|| (UPDATE_PREBINDING_DRY_RUN
& flags
) )
1601 fprintf(stderr
, "update_prebinding: disk space down to %lluMB, committing %lu prebound files\n", freespace
/(1024*1024), updatedImages
.size());
1602 // commit files processed so far, to free up more disk space
1603 commitRepreboundFiles(updatedImages
, true);
1604 // empty list of temp files
1605 updatedImages
.clear();
1609 // commit them, don't need to unmap old, cause we are done
1610 commitRepreboundFiles(updatedImages
, false);
1613 catch (const char* msg
) {
1614 // delete temp files
1616 for (std::vector
<ImageLoader
*>::iterator it
=preboundImages
.begin(); it
!= preboundImages
.end(); it
++) {
1617 (*it
)->reprebindCommit(dyld::gLinkContext
, false, false);
1620 catch (const char* commitMsg
) {
1621 fprintf(stderr
, "update_prebinding: error: %s\n", commitMsg
);
1623 fprintf(stderr
, "update_prebinding: error: %s\n", msg
);
1631 static const struct dyld_all_image_infos
* _dyld_get_all_image_infos()
1633 return &dyld_all_image_infos
;