]> git.saurik.com Git - apple/dyld.git/blob - src/dyldAPIs.cpp
dyld-97.1.tar.gz
[apple/dyld.git] / src / dyldAPIs.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2006 Apple Computer, Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
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
12 * file.
13 *
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.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25 //
26 // This file implements that API's in <mach-o/dyld.h>
27 //
28 //
29
30 #define __STDC_LIMIT_MACROS
31 #include <stddef.h>
32 #include <stdint.h>
33 #include <string.h>
34 #include <sys/param.h>
35 #include <sys/mount.h>
36
37
38 #include <vector>
39 #include <map>
40 #include <algorithm>
41
42 #include <mach/mach.h>
43 #include <sys/time.h>
44 #include <sys/sysctl.h>
45
46 extern "C" mach_port_name_t task_self_trap(void); // can't include <System/mach/mach_traps.h> because it is missing extern C
47
48 #include "mach-o/dyld_images.h"
49 #include "mach-o/dyld.h"
50 #include "mach-o/dyld_priv.h"
51 #include "mach-o/dyld-update-prebinding.h"
52
53 #include "ImageLoader.h"
54 #include "dyld.h"
55 #include "dyldLibSystemInterface.h"
56
57 #undef _POSIX_C_SOURCE
58 #include "dlfcn.h"
59
60
61 #ifndef RTLD_DLL
62 #define RTLD_DLL 0x200 /* Mac OS X 10.5 and later */
63 #endif
64
65 static char sLastErrorFilePath[1024];
66 static NSLinkEditErrors sLastErrorFileCode;
67 static int sLastErrorNo;
68
69
70 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
71 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
72 // This conditional keeps support for old libSystem's which needed some help implementing the API's
73 #define OLD_LIBSYSTEM_SUPPORT (__ppc__ || __i386__)
74
75
76 // The following functions have no prototype in any header. They are special cases
77 // where _dyld_func_lookup() is used directly.
78 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit);
79 #if OLD_LIBSYSTEM_SUPPORT
80 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options);
81 #endif
82 static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions);
83 static void _dyld_fork_child();
84 static void _dyld_make_delayed_module_initializer_calls();
85 static bool NSMakePrivateModulePublic(NSModule module);
86 static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header);
87 static void registerThreadHelpers(const dyld::LibSystemHelpers*);
88 static const struct dyld_all_image_infos* _dyld_get_all_image_infos();
89
90 // The following functions are dyld API's, but since dyld links with a static copy of libc.a
91 // the public name cannot be used.
92 static void client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module);
93 static bool client_NSIsSymbolNameDefined(const char* symbolName);
94
95
96 static void unimplemented()
97 {
98 dyld::halt("unimplemented dyld function\n");
99 }
100
101 struct dyld_func {
102 const char* name;
103 void* implementation;
104 };
105
106 static struct dyld_func dyld_funcs[] = {
107 {"__dyld_register_thread_helpers", (void*)registerThreadHelpers },
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_make_delayed_module_initializer_calls", (void*)_dyld_make_delayed_module_initializer_calls },
111 {"__dyld_fork_child", (void*)_dyld_fork_child },
112 {"__dyld_dyld_register_image_state_change_handler", (void*)dyld_register_image_state_change_handler },
113 {"__dyld_dladdr", (void*)dladdr },
114 {"__dyld_dlclose", (void*)dlclose },
115 {"__dyld_dlerror", (void*)dlerror },
116 {"__dyld_dlopen", (void*)dlopen },
117 {"__dyld_dlsym", (void*)dlsym },
118 {"__dyld_dlopen_preflight", (void*)dlopen_preflight },
119 {"__dyld_get_image_header_containing_address", (void*)_dyld_get_image_header_containing_address },
120 {"__dyld_image_count", (void*)_dyld_image_count },
121 {"__dyld_get_image_header", (void*)_dyld_get_image_header },
122 {"__dyld_get_image_vmaddr_slide", (void*)_dyld_get_image_vmaddr_slide },
123 {"__dyld_get_image_name", (void*)_dyld_get_image_name },
124 {"__dyld__NSGetExecutablePath", (void*)_NSGetExecutablePath },
125
126 // the rest of these are either deprecated or SPIs
127 {"__dyld_lookup_and_bind", (void*)client_dyld_lookup_and_bind },
128 {"__dyld_lookup_and_bind_with_hint", (void*)_dyld_lookup_and_bind_with_hint },
129 {"__dyld_lookup_and_bind_fully", (void*)_dyld_lookup_and_bind_fully },
130 {"__dyld_install_handlers", (void*)_dyld_install_handlers },
131 {"__dyld_link_edit_error", (void*)NSLinkEditError },
132 {"__dyld_unlink_module", (void*)NSUnLinkModule },
133 {"__dyld_bind_objc_module", (void*)_dyld_bind_objc_module },
134 {"__dyld_bind_fully_image_containing_address", (void*)_dyld_bind_fully_image_containing_address },
135 {"__dyld_image_containing_address", (void*)_dyld_image_containing_address },
136 {"__dyld_moninit", (void*)_dyld_moninit },
137 {"__dyld_register_binding_handler", (void*)_dyld_register_binding_handler },
138 {"__dyld_NSNameOfSymbol", (void*)NSNameOfSymbol },
139 {"__dyld_NSAddressOfSymbol", (void*)NSAddressOfSymbol },
140 {"__dyld_NSModuleForSymbol", (void*)NSModuleForSymbol },
141 {"__dyld_NSLookupAndBindSymbol", (void*)NSLookupAndBindSymbol },
142 {"__dyld_NSLookupAndBindSymbolWithHint", (void*)NSLookupAndBindSymbolWithHint },
143 {"__dyld_NSLookupSymbolInModule", (void*)NSLookupSymbolInModule},
144 {"__dyld_NSLookupSymbolInImage", (void*)NSLookupSymbolInImage},
145 {"__dyld_NSMakePrivateModulePublic", (void*)NSMakePrivateModulePublic},
146 {"__dyld_NSIsSymbolNameDefined", (void*)client_NSIsSymbolNameDefined},
147 {"__dyld_NSIsSymbolNameDefinedWithHint", (void*)NSIsSymbolNameDefinedWithHint },
148 {"__dyld_NSIsSymbolNameDefinedInImage", (void*)NSIsSymbolNameDefinedInImage},
149 {"__dyld_NSNameOfModule", (void*)NSNameOfModule },
150 {"__dyld_NSLibraryNameForModule", (void*)NSLibraryNameForModule },
151 {"__dyld_NSAddLibrary", (void*)NSAddLibrary },
152 {"__dyld_NSAddLibraryWithSearching", (void*)NSAddLibraryWithSearching },
153 {"__dyld_NSAddImage", (void*)NSAddImage },
154 {"__dyld_launched_prebound", (void*)_dyld_launched_prebound },
155 {"__dyld_all_twolevel_modules_prebound", (void*)_dyld_all_twolevel_modules_prebound },
156 {"__dyld_call_module_initializers_for_dylib", (void*)_dyld_call_module_initializers_for_dylib },
157 {"__dyld_install_link_edit_symbol_handlers", (void*)dyld::registerZeroLinkHandlers },
158 {"__dyld_NSCreateObjectFileImageFromFile", (void*)NSCreateObjectFileImageFromFile },
159 {"__dyld_NSCreateObjectFileImageFromMemory", (void*)NSCreateObjectFileImageFromMemory },
160 {"__dyld_NSDestroyObjectFileImage", (void*)NSDestroyObjectFileImage },
161 {"__dyld_NSLinkModule", (void*)NSLinkModule },
162 {"__dyld_NSHasModInitObjectFileImage", (void*)NSHasModInitObjectFileImage },
163 {"__dyld_NSSymbolDefinitionCountInObjectFileImage", (void*)NSSymbolDefinitionCountInObjectFileImage },
164 {"__dyld_NSSymbolDefinitionNameInObjectFileImage", (void*)NSSymbolDefinitionNameInObjectFileImage },
165 {"__dyld_NSIsSymbolDefinedInObjectFileImage", (void*)NSIsSymbolDefinedInObjectFileImage },
166 {"__dyld_NSSymbolReferenceNameInObjectFileImage", (void*)NSSymbolReferenceNameInObjectFileImage },
167 {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage },
168 {"__dyld_NSGetSectionDataInObjectFileImage", (void*)NSGetSectionDataInObjectFileImage },
169 {"__dyld_NSFindSectionAndOffsetInObjectFileImage", (void*)NSFindSectionAndOffsetInObjectFileImage },
170 #if OLD_LIBSYSTEM_SUPPORT
171 {"__dyld_link_module", (void*)_dyld_link_module },
172 #endif
173 {"__dyld_dlord", (void*)dlord },
174 {"__dyld_get_all_image_infos", (void*)_dyld_get_all_image_infos },
175 {NULL, 0}
176 };
177
178
179
180 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
181 inline NSSymbol SymbolToNSSymbol(const ImageLoader::Symbol* sym)
182 {
183 return (NSSymbol)sym;
184 }
185 inline const ImageLoader::Symbol* NSSymbolToSymbol(NSSymbol sym)
186 {
187 return (const ImageLoader::Symbol*)sym;
188 }
189
190 // dyld's abstract type NSModule is implemented as ImageLoader*
191 inline NSModule ImageLoaderToNSModule(const ImageLoader* image)
192 {
193 return (NSModule)image;
194 }
195 inline ImageLoader* NSModuleToImageLoader(NSModule module)
196 {
197 ImageLoader* image = (ImageLoader*)module;
198 if ( dyld::validImage(image) )
199 return image;
200 return NULL;
201 }
202
203 // actual definition for opaque type
204 struct __NSObjectFileImage
205 {
206 ImageLoader* image;
207 const void* imageBaseAddress; // not used with OFI created from files
208 size_t imageLength; // not used with OFI created from files
209 };
210 static std::vector<NSObjectFileImage> sObjectFileImages;
211
212
213
214 //
215 // __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
216 // The contained image is delete in one of two places:
217 // NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
218 // NSDestroyObjectFileImage deletes the image if image is not in list of valid images
219 //
220
221
222 static void dyldAPIhalt(const char* apiName, const char* errorMsg)
223 {
224 dyld::log("dyld: %s() error\n", apiName);
225 dyld::halt(errorMsg);
226 }
227
228
229
230 static void setLastError(NSLinkEditErrors code, int errnum, const char* file, const char* message)
231 {
232 dyld::setErrorMessage(message);
233 strncpy(sLastErrorFilePath, file, 1024);
234 sLastErrorFilePath[1023] = '\0';
235 sLastErrorFileCode = code;
236 sLastErrorNo = errnum;
237 }
238
239
240 /*
241 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
242 * copies the path of the executable into the buffer and returns 0 if the path
243 * was successfully copied in the provided buffer. If the buffer is not large
244 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
245 * Note that _NSGetExecutablePath will return "a path" to the executable not a
246 * "real path" to the executable. That is the path may be a symbolic link and
247 * not the real file. And with deep directories the total bufsize needed could
248 * be more than MAXPATHLEN.
249 */
250 int _NSGetExecutablePath(char* buf, uint32_t *bufsize)
251 {
252 if ( dyld::gLogAPIs )
253 dyld::log("%s(...)\n", __func__);
254 const char* exePath = dyld::getExecutablePath();
255 if(*bufsize < strlen(exePath) + 1){
256 *bufsize = strlen(exePath) + 1;
257 return -1;
258 }
259 strcpy(buf, exePath);
260 return 0;
261 }
262
263
264 //
265 // _dyld_call_module_initializers_for_dylib() is the dyld side of
266 // __initialize_Cplusplus() which is in dylib1.o.
267 // It is intended to only be called inside -init rouintes.
268 // -init routines are called before module initializers (what C++
269 // initializers use). Calling __initialize_Cplusplus() in a -init
270 // routine causes the module initializers for an image to be called
271 // which then allows C++ to be used inside a -init routine
272 //
273 static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header)
274 {
275 if ( dyld::gLogAPIs )
276 dyld::log("__initialize_Cplusplus()\n");
277
278 // for now, do nothing...
279 }
280
281
282 void _dyld_lookup_and_bind_fully(const char* symbolName, void** address, NSModule* module)
283 {
284 if ( dyld::gLogAPIs )
285 dyld::log("%s(\"%s\", %p, %p)\n", __func__, symbolName, address, module);
286 ImageLoader* image;
287 const ImageLoader::Symbol* sym;
288 dyld::clearErrorMessage();
289 if ( dyld::flatFindExportedSymbol(symbolName, &sym, (const ImageLoader**)&image) ) {
290 try {
291 image->bindAllLazyPointers(dyld::gLinkContext, true);
292 if ( address != NULL)
293 *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
294 if ( module != NULL)
295 *module = ImageLoaderToNSModule(image);
296 }
297 catch (const char* msg) {
298 dyldAPIhalt(__func__, msg);
299 }
300 }
301 else {
302 // on failure to find symbol return NULLs
303 if ( address != NULL)
304 *address = NULL;
305 if ( module != NULL)
306 *module = NULL;
307 }
308 }
309
310 // Note: This cannot have public name because dyld is built with a static copy of libc.a
311 // which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
312 static void client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module)
313 {
314 if ( dyld::gLogAPIs )
315 dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName, address, module);
316 const ImageLoader* image;
317 const ImageLoader::Symbol* sym;
318 if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
319 if ( address != NULL)
320 *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
321 if ( module != NULL)
322 *module = ImageLoaderToNSModule(image);
323 }
324 else {
325 // on failure to find symbol return NULLs
326 if ( address != NULL)
327 *address = NULL;
328 if ( module != NULL)
329 *module = NULL;
330 }
331 }
332
333 void _dyld_lookup_and_bind_with_hint(const char* symbolName, const char* library_name_hint, void** address, NSModule* module)
334 {
335 if ( dyld::gLogAPIs )
336 dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__, symbolName, library_name_hint, address, module);
337 const ImageLoader* image;
338 const ImageLoader::Symbol* sym;
339 // Look for library whose path contains the hint. If that fails search everywhere
340 if ( dyld::flatFindExportedSymbolWithHint(symbolName, library_name_hint, &sym, &image)
341 || dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
342 if ( address != NULL)
343 *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
344 if ( module != NULL)
345 *module = ImageLoaderToNSModule(image);
346 }
347 else {
348 // on failure to find symbol return NULLs
349 if ( address != NULL)
350 *address = NULL;
351 if ( module != NULL)
352 *module = NULL;
353 }
354 }
355
356
357 NSSymbol NSLookupAndBindSymbol(const char *symbolName)
358 {
359 if ( dyld::gLogAPIs )
360 dyld::log("%s(\"%s\")\n", __func__, symbolName);
361 const ImageLoader* image;
362 const ImageLoader::Symbol* sym;
363 if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
364 return SymbolToNSSymbol(sym);
365 }
366 // return NULL on failure
367 return NULL;
368 }
369
370 NSSymbol NSLookupAndBindSymbolWithHint(const char* symbolName, const char* libraryNameHint)
371 {
372 if ( dyld::gLogAPIs )
373 dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
374 const ImageLoader* image;
375 const ImageLoader::Symbol* sym;
376 bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
377 if ( ! found ) {
378 // hint failed, do slow search of all images
379 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
380 }
381 if ( found )
382 return SymbolToNSSymbol(sym);
383
384 // return NULL on failure and log
385 if ( dyld::gLogAPIs )
386 dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__, symbolName, libraryNameHint);
387 return NULL;
388 }
389
390 uint32_t _dyld_image_count(void)
391 {
392 if ( dyld::gLogAPIs )
393 dyld::log("%s()\n", __func__);
394 return dyld::getImageCount();
395 }
396
397 const struct mach_header* _dyld_get_image_header(uint32_t image_index)
398 {
399 if ( dyld::gLogAPIs )
400 dyld::log("%s(%u)\n", __func__, image_index);
401 ImageLoader* image = dyld::getIndexedImage(image_index);
402 if ( image != NULL )
403 return (struct mach_header*)image->machHeader();
404 else
405 return NULL;
406 }
407
408
409 static __attribute__((noinline))
410 const struct mach_header* addImage(void* callerAddress, const char* path, bool search, bool dontLoad, bool matchInstallName, bool abortOnError)
411 {
412 ImageLoader* image = NULL;
413 std::vector<const char*> rpathsFromCallerImage;
414 try {
415 dyld::clearErrorMessage();
416 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
417 // like dlopen, use rpath from caller image and from main executable
418 if ( callerImage != NULL )
419 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
420 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
421 if ( callerImage != dyld::mainExecutable() ) {
422 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
423 }
424 dyld::LoadContext context;
425 context.useSearchPaths = search;
426 context.useLdLibraryPath = false;
427 context.implicitRPath = false;
428 context.matchByInstallName = matchInstallName;
429 context.dontLoad = dontLoad;
430 context.mustBeBundle = false;
431 context.mustBeDylib = true;
432 context.findDLL = false;
433 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
434 context.rpath = &callersRPaths; // rpaths from caller and main executable
435
436 image = load(path, context);
437 if ( image != NULL ) {
438 if ( context.matchByInstallName )
439 image->setMatchInstallPath(true);
440 dyld::link(image, false, callersRPaths);
441 dyld::runInitializers(image);
442 // images added with NSAddImage() can never be unloaded
443 image->setNeverUnload();
444 }
445 }
446 catch (const char* msg) {
447 dyld::garbageCollectImages();
448 if ( abortOnError) {
449 char pathMsg[strlen(msg)+strlen(path)+4];
450 strcpy(pathMsg, msg);
451 strcat(pathMsg, " ");
452 strcat(pathMsg, path);
453 dyldAPIhalt("NSAddImage", pathMsg);
454 }
455 // not halting, so set error state for NSLinkEditError to find
456 setLastError(NSLinkEditOtherError, 0, path, msg);
457 free((void*)msg); // our free() will do nothing if msg is a string literal
458 image = NULL;
459 }
460 // free rpaths (getRPaths() malloc'ed each string)
461 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
462 const char* str = *it;
463 free((void*)str);
464 }
465 if ( image == NULL )
466 return NULL;
467 else
468 return image->machHeader();
469 }
470
471
472 const struct mach_header* NSAddImage(const char* path, uint32_t options)
473 {
474 if ( dyld::gLogAPIs )
475 dyld::log("%s(\"%s\", 0x%08X)\n", __func__, path, options);
476 const bool dontLoad = ( (options & NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED) != 0 );
477 const bool search = ( (options & NSADDIMAGE_OPTION_WITH_SEARCHING) != 0 );
478 const bool matchInstallName = ( (options & NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME) != 0 );
479 const bool abortOnError = ( (options & NSADDIMAGE_OPTION_RETURN_ON_ERROR|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED) == 0 );
480 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
481 return addImage(callerAddress, path, search, dontLoad, matchInstallName, abortOnError);
482 }
483
484 bool NSAddLibrary(const char* path)
485 {
486 if ( dyld::gLogAPIs )
487 dyld::log("%s(\"%s\")\n", __func__, path);
488 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
489 return (addImage(callerAddress, path, false, false, false, false) != NULL);
490 }
491
492 bool NSAddLibraryWithSearching(const char* path)
493 {
494 if ( dyld::gLogAPIs )
495 dyld::log("%s(\"%s\")\n", __func__, path);
496 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
497 return (addImage(callerAddress, path, true, false, false, false) != NULL);
498 }
499
500
501
502 //#define NSADDIMAGE_OPTION_NONE 0x0
503 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
504 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
505
506 bool NSIsSymbolNameDefinedInImage(const struct mach_header* mh, const char* symbolName)
507 {
508 if ( dyld::gLogAPIs )
509 dyld::log("%s(%p, \"%s\")\n", __func__, (void *)mh, symbolName);
510 ImageLoader* image = dyld::findImageByMachHeader(mh);
511 if ( image != NULL ) {
512 if ( image->findExportedSymbol(symbolName, NULL, true, NULL) != NULL)
513 return true;
514 }
515 return false;
516 }
517
518 NSSymbol NSLookupSymbolInImage(const struct mach_header* mh, const char* symbolName, uint32_t options)
519 {
520 if ( dyld::gLogAPIs )
521 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, mh, symbolName, options);
522 const ImageLoader::Symbol* symbol = NULL;
523 dyld::clearErrorMessage();
524 ImageLoader* image = dyld::findImageByMachHeader(mh);
525 if ( image != NULL ) {
526 try {
527 if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY ) {
528 image->bindAllLazyPointers(dyld::gLinkContext, true);
529 }
530 else if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW ) {
531 image->bindAllLazyPointers(dyld::gLinkContext, false);
532 }
533 }
534 catch (const char* msg) {
535 if ( (options & NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR) == 0 ) {
536 dyldAPIhalt(__func__, msg);
537 }
538 }
539 symbol = image->findExportedSymbol(symbolName, NULL, true, NULL);
540 }
541 if ( dyld::gLogAPIs && (symbol == NULL) )
542 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__, mh, symbolName, options);
543 return SymbolToNSSymbol(symbol);
544 }
545
546
547 // Note: This cannot have public name because dyld is built with a static copy of libc.a
548 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
549 static bool client_NSIsSymbolNameDefined(const char* symbolName)
550 {
551 if ( dyld::gLogAPIs )
552 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName);
553 const ImageLoader* image;
554 const ImageLoader::Symbol* sym;
555 return dyld::flatFindExportedSymbol(symbolName, &sym, &image);
556 }
557
558 bool NSIsSymbolNameDefinedWithHint(const char* symbolName, const char* libraryNameHint)
559 {
560 if ( dyld::gLogAPIs )
561 dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
562 const ImageLoader* image;
563 const ImageLoader::Symbol* sym;
564 bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
565 if ( ! found ) {
566 // hint failed, do slow search of all images
567 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
568 }
569 if ( !found && dyld::gLogAPIs )
570 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__, symbolName, libraryNameHint);
571 return found;
572 }
573
574 const char* NSNameOfSymbol(NSSymbol symbol)
575 {
576 if ( dyld::gLogAPIs )
577 dyld::log("%s(%p)\n", __func__, (void *)symbol);
578 const char* result = NULL;
579 ImageLoader* image = dyld::findImageContainingAddress(symbol);
580 if ( image != NULL )
581 result = image->getExportedSymbolName(NSSymbolToSymbol(symbol));
582 return result;
583 }
584
585 void* NSAddressOfSymbol(NSSymbol symbol)
586 {
587 if ( dyld::gLogAPIs )
588 dyld::log("%s(%p)\n", __func__, (void *)symbol);
589 void* result = NULL;
590 ImageLoader* image = dyld::findImageContainingAddress(symbol);
591 if ( image != NULL )
592 result = (void*)image->getExportedSymbolAddress(NSSymbolToSymbol(symbol), dyld::gLinkContext);
593 return result;
594 }
595
596 NSModule NSModuleForSymbol(NSSymbol symbol)
597 {
598 if ( dyld::gLogAPIs )
599 dyld::log("%s(%p)\n", __func__, (void *)symbol);
600 NSModule result = NULL;
601 ImageLoader* image = dyld::findImageContainingAddress(symbol);
602 if ( image != NULL )
603 result = ImageLoaderToNSModule(image);
604 return result;
605 }
606
607
608 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index)
609 {
610 if ( dyld::gLogAPIs )
611 dyld::log("%s(%u)\n", __func__, image_index);
612 ImageLoader* image = dyld::getIndexedImage(image_index);
613 if ( image != NULL )
614 return image->getSlide();
615 else
616 return 0;
617 }
618
619 const char* _dyld_get_image_name(uint32_t image_index)
620 {
621 if ( dyld::gLogAPIs )
622 dyld::log("%s(%u)\n", __func__, image_index);
623 ImageLoader* image = dyld::getIndexedImage(image_index);
624 if ( image != NULL )
625 return image->getLogicalPath();
626 else
627 return NULL;
628 }
629
630
631
632 bool _dyld_all_twolevel_modules_prebound(void)
633 {
634 if ( dyld::gLogAPIs )
635 dyld::log("%s()\n", __func__);
636 return FALSE; // fixme
637 }
638
639 void _dyld_bind_objc_module(const void *objc_module)
640 {
641 if ( dyld::gLogAPIs )
642 dyld::log("%s(%p)\n", __func__, objc_module);
643 // do nothing, with new dyld everything already bound
644 }
645
646
647 bool _dyld_bind_fully_image_containing_address(const void* address)
648 {
649 if ( dyld::gLogAPIs )
650 dyld::log("%s(%p)\n", __func__, address);
651 dyld::clearErrorMessage();
652 ImageLoader* image = dyld::findImageContainingAddress(address);
653 if ( image != NULL ) {
654 try {
655 image->bindAllLazyPointers(dyld::gLinkContext, true);
656 return true;
657 }
658 catch (const char* msg) {
659 dyldAPIhalt(__func__, msg);
660 }
661 }
662 return false;
663 }
664
665 bool _dyld_image_containing_address(const void* address)
666 {
667 if ( dyld::gLogAPIs )
668 dyld::log("%s(%p)\n", __func__, address);
669 ImageLoader *imageLoader = dyld::findImageContainingAddress(address);
670 return (NULL != imageLoader);
671 }
672
673 static NSObjectFileImage createObjectImageFile(ImageLoader* image, const void* address = NULL, size_t len=0)
674 {
675 NSObjectFileImage result = new __NSObjectFileImage();
676 result->image = image;
677 result->imageBaseAddress = address;
678 result->imageLength = len;
679 sObjectFileImages.push_back(result);
680 return result;
681 }
682
683 NSObjectFileImageReturnCode NSCreateObjectFileImageFromFile(const char* pathName, NSObjectFileImage *objectFileImage)
684 {
685 if ( dyld::gLogAPIs )
686 dyld::log("%s(\"%s\", ...)\n", __func__, pathName);
687 try {
688 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
689 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
690
691 dyld::LoadContext context;
692 context.useSearchPaths = false;
693 context.useLdLibraryPath = false;
694 context.implicitRPath = false;
695 context.matchByInstallName = false;
696 context.dontLoad = false;
697 context.mustBeBundle = true;
698 context.mustBeDylib = false;
699 context.findDLL = false;
700 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
701 context.rpath = NULL; // support not yet implemented
702
703 ImageLoader* image = dyld::load(pathName, context);
704 // Note: We DO NOT link the image! NSLinkModule will do that
705 if ( image != NULL ) {
706 if ( !image->isBundle() ) {
707 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
708 return NSObjectFileImageInappropriateFile;
709 }
710 *objectFileImage = createObjectImageFile(image);
711 return NSObjectFileImageSuccess;
712 }
713 }
714 catch (const char* msg) {
715 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
716 dyld::garbageCollectImages();
717 free((void*)msg);
718 return NSObjectFileImageInappropriateFile;
719 }
720 return NSObjectFileImageFailure;
721 }
722
723
724 NSObjectFileImageReturnCode NSCreateObjectFileImageFromMemory(const void* address, size_t size, NSObjectFileImage *objectFileImage)
725 {
726 if ( dyld::gLogAPIs )
727 dyld::log("%s(%p, %lu, %p)\n", __func__, address, size, objectFileImage);
728
729 try {
730 ImageLoader* image = dyld::loadFromMemory((const uint8_t*)address, size, NULL);
731 if ( ! image->isBundle() ) {
732 // this API can only be used with bundles...
733 dyld::garbageCollectImages();
734 return NSObjectFileImageInappropriateFile;
735 }
736 // Note: We DO NOT link the image! NSLinkModule will do that
737 if ( image != NULL ) {
738 *objectFileImage = createObjectImageFile(image, address, size);
739 return NSObjectFileImageSuccess;
740 }
741 }
742 catch (const char* msg) {
743 free((void*)msg);
744 dyld::garbageCollectImages();
745 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
746 }
747 return NSObjectFileImageFailure;
748 }
749
750 static bool validOFI(NSObjectFileImage objectFileImage)
751 {
752 const int ofiCount = sObjectFileImages.size();
753 for (int i=0; i < ofiCount; ++i) {
754 if ( sObjectFileImages[i] == objectFileImage )
755 return true;
756 }
757 return false;
758 }
759
760 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage)
761 {
762 if ( dyld::gLogAPIs )
763 dyld::log("%s(%p)\n", __func__, objectFileImage);
764
765 if ( validOFI(objectFileImage) ) {
766 // a failure during NSLinkModule will delete the image
767 if ( objectFileImage->image != NULL ) {
768 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
769 // and we should delete it
770 bool linkedImage = dyld::validImage(objectFileImage->image);
771 if ( ! linkedImage ) {
772 delete objectFileImage->image;
773 objectFileImage->image = NULL;
774 }
775 }
776
777 // remove from list of ofi's
778 for (std::vector<NSObjectFileImage>::iterator it=sObjectFileImages.begin(); it != sObjectFileImages.end(); it++) {
779 if ( *it == objectFileImage ) {
780 sObjectFileImages.erase(it);
781 break;
782 }
783 }
784
785 // if object was created from a memory, release that memory
786 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
787 if ( objectFileImage->imageBaseAddress != NULL ) {
788 vm_deallocate(mach_task_self(), (vm_address_t)objectFileImage->imageBaseAddress, objectFileImage->imageLength);
789 }
790
791 // free ofi object
792 delete objectFileImage;
793
794 return true;
795 }
796 return false;
797 }
798
799 bool NSHasModInitObjectFileImage(NSObjectFileImage objectFileImage)
800 {
801 if ( dyld::gLogAPIs )
802 dyld::log("%s(%p)\n", __func__, objectFileImage);
803 return objectFileImage->image->needsInitialization();
804 }
805
806 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage)
807 {
808 if ( dyld::gLogAPIs )
809 dyld::log("%s(%p)\n", __func__, objectFileImage);
810 return objectFileImage->image->getExportedSymbolCount();
811 }
812
813 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal)
814 {
815 if ( dyld::gLogAPIs )
816 dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
817 const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedExportedSymbol(ordinal);
818 return objectFileImage->image->getExportedSymbolName(sym);
819 }
820
821 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage)
822 {
823 if ( dyld::gLogAPIs )
824 dyld::log("%s(%p)\n", __func__, objectFileImage);
825 return objectFileImage->image->getImportedSymbolCount();
826 }
827
828 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal,
829 bool* tentative_definition)
830 {
831 if ( dyld::gLogAPIs )
832 dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
833 const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedImportedSymbol(ordinal);
834 if ( tentative_definition != NULL ) {
835 ImageLoader::ReferenceFlags flags = objectFileImage->image->geImportedSymbolInfo(sym);
836 if ( (flags & ImageLoader::kTentativeDefinition) != 0 )
837 *tentative_definition = true;
838 else
839 *tentative_definition = false;
840 }
841 return objectFileImage->image->getImportedSymbolName(sym);
842 }
843
844 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage,
845 const char* segmentName, const char* sectionName, unsigned long* size)
846 {
847 if ( dyld::gLogAPIs )
848 dyld::log("%s(%p,%s, %s)\n", __func__, objectFileImage, segmentName, sectionName);
849
850 void* start;
851 size_t length;
852 if ( objectFileImage->image->getSectionContent(segmentName, sectionName, &start, &length) ) {
853 if ( size != NULL )
854 *size = length;
855 return start;
856 }
857 return NULL;
858 }
859
860
861
862 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage, const char* symbolName)
863 {
864 if ( dyld::gLogAPIs )
865 dyld::log("%s(%p,%s)\n", __func__, objectFileImage, symbolName);
866 const ImageLoader::Symbol* sym = objectFileImage->image->findExportedSymbol(symbolName, NULL, true, NULL);
867 return ( sym != NULL );
868 }
869
870 /*
871 * Given an imageOffset into an ObjectFileImage, returns
872 * the segment/section name and offset into that section of
873 * that imageOffset. Returns FALSE if the imageOffset is not
874 * in any section. You can used the resulting sectionOffset to
875 * index into the data returned by NSGetSectionDataInObjectFileImage.
876 *
877 * First appeared in Mac OS X 10.3
878 *
879 * SPI: currently only used by ZeroLink to detect +load methods
880 */
881 bool
882 NSFindSectionAndOffsetInObjectFileImage(NSObjectFileImage objectFileImage,
883 unsigned long imageOffset,
884 const char** segmentName, /* can be NULL */
885 const char** sectionName, /* can be NULL */
886 unsigned long* sectionOffset) /* can be NULL */
887 {
888 if ( dyld::gLogAPIs )
889 dyld::log("%s(%p)\n", __func__, objectFileImage);
890
891 return objectFileImage->image->findSection(((char*)(objectFileImage->image->machHeader()))+imageOffset, segmentName, sectionName, sectionOffset);
892 }
893
894
895
896 NSModule NSLinkModule(NSObjectFileImage objectFileImage, const char* moduleName, uint32_t options)
897 {
898 if ( dyld::gLogAPIs )
899 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, objectFileImage, moduleName, options);
900
901 dyld::clearErrorMessage();
902 try {
903 // NSLinkModule allows a bundle to be link multpile times
904 // each link causes the bundle to be copied to a new address
905 if ( objectFileImage->image->isLinked() ) {
906 // already linked, so clone a new one and link it
907 #if 0
908 dyld::warn("%s(0x%08X, \"%s\", 0x%08X) called more than once for 0x%08X\n",
909 __func__, objectFileImage, moduleName, options, objectFileImage);
910 #endif
911 objectFileImage->image = dyld::cloneImage(objectFileImage->image);
912 }
913
914 // if this ofi was made with NSCreateObjectFileImageFromFile() then physical path is already set
915 // if this ofi was create with NSCreateObjectFileImageFromMemory() then the phyiscal path should be set if supplied
916 if ( (options & NSLINKMODULE_OPTION_TRAILING_PHYS_NAME) != 0 ) {
917 if ( objectFileImage->imageBaseAddress != NULL ) {
918 const char* physEnd = &moduleName[strlen(moduleName)+1];
919 objectFileImage->image->setPath(physEnd);
920 }
921 }
922
923 // set moduleName as the name anyone calling _dyld_get_image_name() will see
924 objectFileImage->image->setLogicalPath(moduleName);
925
926 // support private bundles
927 if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
928 objectFileImage->image->setHideExports();
929
930 // set up linking options
931 bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
932
933 // load libraries, rebase, bind, to make this image usable
934 dyld::link(objectFileImage->image, forceLazysBound, ImageLoader::RPathChain(NULL,NULL));
935
936 // run initializers unless magic flag says not to
937 if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
938 dyld::runInitializers(objectFileImage->image);
939
940 // bump reference count to keep this bundle from being garbage collected
941 objectFileImage->image->incrementDlopenReferenceCount();
942
943 return ImageLoaderToNSModule(objectFileImage->image);
944 }
945 catch (const char* msg) {
946 dyld::garbageCollectImages();
947 if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
948 dyldAPIhalt(__func__, msg);
949 // not halting, so set error state for NSLinkEditError to find
950 setLastError(NSLinkEditOtherError, 0, moduleName, msg);
951 // dyld::link() deleted the image so lose our reference
952 objectFileImage->image = NULL;
953 free((void*)msg);
954 return NULL;
955 }
956 }
957
958
959 #if OLD_LIBSYSTEM_SUPPORT
960 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
961 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options)
962 {
963 if ( dyld::gLogAPIs )
964 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr, moduleName, options); // note name/args translation
965 ImageLoader* image = NULL;
966 dyld::clearErrorMessage();
967 try {
968 const char* imageName = moduleName;
969 if ( (options & NSLINKMODULE_OPTION_TRAILING_PHYS_NAME) != 0 )
970 imageName = &moduleName[strlen(moduleName)+1];
971
972 image = dyld::loadFromMemory((const uint8_t*)object_addr, object_size, imageName);
973
974 if ( (options & NSLINKMODULE_OPTION_TRAILING_PHYS_NAME) != 0 )
975 image->setLogicalPath(moduleName);
976
977 if ( image != NULL ) {
978 // support private bundles
979 if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
980 image->setHideExports();
981
982 // set up linking options
983 bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
984
985 // load libraries, rebase, bind, to make this image usable
986 dyld::link(image, forceLazysBound, ImageLoader::RPathChain(NULL,NULL));
987
988 // run initializers unless magic flag says not to
989 if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
990 dyld::runInitializers(image);
991 }
992 }
993 catch (const char* msg) {
994 if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
995 dyldAPIhalt("NSLinkModule", msg);
996 // not halting, so set error state for NSLinkEditError to find
997 setLastError(NSLinkEditOtherError, 0, moduleName, msg);
998 // if image was created for this bundle, destroy it
999 if ( image != NULL ) {
1000 dyld::removeImage(image);
1001 delete image;
1002 }
1003 image = NULL;
1004 free((void*)msg);
1005 }
1006 return ImageLoaderToNSModule(image);
1007 }
1008 #endif
1009
1010 NSSymbol NSLookupSymbolInModule(NSModule module, const char* symbolName)
1011 {
1012 if ( dyld::gLogAPIs )
1013 dyld::log("%s(%p, \"%s\")\n", __func__, (void *)module, symbolName);
1014 ImageLoader* image = NSModuleToImageLoader(module);
1015 if ( image == NULL )
1016 return NULL;
1017 return SymbolToNSSymbol(image->findExportedSymbol(symbolName, NULL, false, NULL));
1018 }
1019
1020 const char* NSNameOfModule(NSModule module)
1021 {
1022 if ( dyld::gLogAPIs )
1023 dyld::log("%s(%p)\n", __func__, module);
1024 ImageLoader* image = NSModuleToImageLoader(module);
1025 if ( image == NULL )
1026 return NULL;
1027 return image->getPath();
1028 }
1029
1030 const char* NSLibraryNameForModule(NSModule module)
1031 {
1032 if ( dyld::gLogAPIs )
1033 dyld::log("%s(%p)\n", __func__, module);
1034 ImageLoader* image = NSModuleToImageLoader(module);
1035 if ( image == NULL )
1036 return NULL;
1037 return image->getPath();
1038 }
1039
1040 bool NSUnLinkModule(NSModule module, uint32_t options)
1041 {
1042 if ( dyld::gLogAPIs )
1043 dyld::log("%s(%p, 0x%08X)\n", __func__, module, options);
1044 if ( module == NULL )
1045 return false;
1046 ImageLoader* image = NSModuleToImageLoader(module);
1047 if ( image == NULL )
1048 return false;
1049 dyld::removeImage(image);
1050
1051 if ( (options & NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED) != 0 )
1052 image->setLeaveMapped();
1053
1054 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1055
1056 // Only delete image if there is no ofi referencing it
1057 // That means the ofi was destroyed after linking, so no one is left to delete this image
1058 const int ofiCount = sObjectFileImages.size();
1059 bool found = false;
1060 for (int i=0; i < ofiCount; ++i) {
1061 NSObjectFileImage ofi = sObjectFileImages[i];
1062 if ( ofi->image == image )
1063 found = true;
1064 }
1065 if ( !found )
1066 delete image;
1067
1068 return true;
1069 }
1070
1071 // internal name and parameters do not match public name and parameters...
1072 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit)
1073 {
1074 if ( dyld::gLogAPIs )
1075 dyld::log("NSLinkEditErrorHandlers()\n");
1076
1077 dyld::registerUndefinedHandler((dyld::UndefinedHandler)undefined);
1078 // no support for multiple or linkedit handlers
1079 }
1080
1081 const struct mach_header * _dyld_get_image_header_containing_address(const void* address)
1082 {
1083 if ( dyld::gLogAPIs )
1084 dyld::log("%s(%p)\n", __func__, address);
1085 ImageLoader* image = dyld::findImageContainingAddress(address);
1086 if ( image != NULL )
1087 return image->machHeader();
1088 return NULL;
1089 }
1090
1091
1092 void _dyld_register_func_for_add_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
1093 {
1094 if ( dyld::gLogAPIs )
1095 dyld::log("%s(%p)\n", __func__, (void *)func);
1096 dyld::registerAddCallback(func);
1097 }
1098
1099 void _dyld_register_func_for_remove_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
1100 {
1101 if ( dyld::gLogAPIs )
1102 dyld::log("%s(%p)\n", __func__, (void *)func);
1103 dyld::registerRemoveCallback(func);
1104 }
1105
1106
1107 // called by crt before main
1108 static void _dyld_make_delayed_module_initializer_calls()
1109 {
1110 if ( dyld::gLogAPIs )
1111 dyld::log("%s()\n", __func__);
1112
1113 #if SUPPORT_OLD_CRT_INITIALIZATION
1114 if ( dyld::gRunInitializersOldWay )
1115 dyld::initializeMainExecutable();
1116 #endif
1117 }
1118
1119
1120 void NSLinkEditError(NSLinkEditErrors* c, int* errorNumber, const char** fileName, const char** errorString)
1121 {
1122 // FIXME FIXME
1123 *c = sLastErrorFileCode;
1124 *errorNumber = sLastErrorNo;
1125 *fileName = sLastErrorFilePath;
1126 *errorString = dyld::getErrorMessage();
1127 }
1128
1129 static void _dyld_register_binding_handler(void * (*bindingHandler)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions)
1130 {
1131 if ( dyld::gLogAPIs )
1132 dyld::log("%s()\n", __func__);
1133 dyld::gLinkContext.bindingHandler = bindingHandler;
1134 dyld::gLinkContext.bindingOptions = bindingOptions;
1135 }
1136
1137
1138 // Call by fork() in libSystem after the kernel trap is done on the child side
1139 static void _dyld_fork_child()
1140 {
1141 if ( dyld::gLogAPIs )
1142 dyld::log("%s()\n", __func__);
1143 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1144 // in libSystem for the child of a fork. But dyld is built with a static copy
1145 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1146 //
1147 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1148 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1149 //
1150 extern mach_port_t mach_task_self_;
1151 mach_task_self_ = task_self_trap();
1152 }
1153
1154
1155
1156 typedef void (*MonitorProc)(char *lowpc, char *highpc);
1157
1158 static void monInitCallback(ImageLoader* image, void* userData)
1159 {
1160 MonitorProc proc = (MonitorProc)userData;
1161 void* start;
1162 size_t length;
1163 if ( image->getSectionContent("__TEXT", "__text", &start, &length) ) {
1164 proc((char*)start, (char*)start+length);
1165 }
1166 }
1167
1168 //
1169 // _dyld_moninit is called from profiling runtime routine moninit().
1170 // dyld calls back with the range of each __TEXT/__text section in every
1171 // linked image.
1172 //
1173 void _dyld_moninit(MonitorProc proc)
1174 {
1175 dyld::forEachImageDo(&monInitCallback, (void*)proc);
1176 }
1177
1178 // returns true if prebinding was used in main executable
1179 bool _dyld_launched_prebound()
1180 {
1181 if ( dyld::gLogAPIs )
1182 dyld::log("%s()\n", __func__);
1183
1184 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1185 return dyld::mainExecutablePrebound();
1186 }
1187
1188
1189 //
1190 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1191 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1192 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1193 // flag on the image for this module. If the module was found and it was
1194 // private then everything worked and TRUE is returned else FALSE is returned.
1195 //
1196 static bool NSMakePrivateModulePublic(NSModule module)
1197 {
1198 ImageLoader* image = NSModuleToImageLoader(module);
1199 if ( image != NULL ) {
1200 if ( image->hasHiddenExports() ) {
1201 image->setHideExports(false);
1202 return true;
1203 }
1204 }
1205 return false;
1206 }
1207
1208
1209
1210 bool lookupDyldFunction(const char* name, uintptr_t* address)
1211 {
1212 for (const dyld_func* p = dyld_funcs; p->name != NULL; ++p) {
1213 if ( strcmp(p->name, name) == 0 ) {
1214 if( p->implementation == unimplemented )
1215 dyld::log("unimplemented dyld function: %s\n", p->name);
1216 *address = (uintptr_t)p->implementation;
1217 return true;
1218 }
1219 }
1220 *address = 0;
1221 return false;
1222 }
1223
1224 static bool readOnlyBootVolume()
1225 {
1226 struct statfs sfs;
1227 if ( statfs("/", &sfs) == 0 ) {
1228 return ( sfs.f_flags & MNT_RDONLY );
1229 }
1230 // if statfs() fails, something is wrong, so don't rebuild dyld cache
1231 return true;
1232 }
1233
1234
1235 static void registerThreadHelpers(const dyld::LibSystemHelpers* helpers)
1236 {
1237 dyld::gLibSystemHelpers = helpers;
1238
1239 #if DYLD_SHARED_CACHE_SUPPORT
1240 // notify dyld server if something is wrong with the shared cache
1241 //dyld::log("helpers->version=%lu, gSharedCacheDontNotify=%d, gSharedCacheNotFound=%d, gSharedCacheNeedsUpdating=%d, readOnlyBootVolume()=%d\n",
1242 // helpers->version, dyld::gSharedCacheDontNotify, dyld::gSharedCacheNotFound, dyld::gSharedCacheNeedsUpdating, readOnlyBootVolume());
1243 if ( (helpers != NULL) && (helpers->version >= 3) && !dyld::gSharedCacheDontNotify ) {
1244 if ( dyld::gSharedCacheNotFound || dyld::gSharedCacheNeedsUpdating ) {
1245 if ( ! readOnlyBootVolume() ) {
1246 if ( dyld::gSharedCacheNotFound )
1247 (*helpers->dyld_shared_cache_missing)();
1248 else if ( dyld::imMemorySharedCacheHeader() == NULL ) {
1249 // since shared cache is not mapped and not missing, it must be
1250 // corrupt. Don't need to test contents, just
1251 // ping launchd to start update_dyld_shared_cache
1252 // rdar://problem/5694507
1253 (*helpers->dyld_shared_cache_out_of_date)();
1254 }
1255 else if ( dyld::gSharedCacheNeedsUpdating ) {
1256 // To reduce the storm of messages to update_dyld_shared_cache
1257 // don't message if the cache file is missing (which means the cache is in
1258 // the process of being regenerated) or if the contents of the cache file
1259 // don't match what is already in memory (which means the cache has
1260 // already be regenerated).
1261 int fd = dyld::openSharedCacheFile();
1262 if ( fd != -1 ) {
1263 uint8_t onDiskCache[4096];
1264 if ( ::read(fd, onDiskCache, 4096) == 4096 ) {
1265 if ( ::memcmp(onDiskCache, dyld::imMemorySharedCacheHeader(), 4096) == 0 ) {
1266 // ping launchd to start update_dyld_shared_cache
1267 (*helpers->dyld_shared_cache_out_of_date)();
1268 }
1269 }
1270 ::close(fd);
1271 }
1272 }
1273 }
1274 }
1275 }
1276 #endif
1277 }
1278
1279
1280 static void dlerrorClear()
1281 {
1282 if ( dyld::gLibSystemHelpers != NULL ) {
1283 // first char of buffer is flag whether string (starting at second char) is valid
1284 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
1285 buffer[0] = '\0';
1286 buffer[1] = '\0';
1287 }
1288 }
1289
1290 static void dlerrorSet(const char* msg)
1291 {
1292 if ( dyld::gLibSystemHelpers != NULL ) {
1293 // first char of buffer is flag whether string (starting at second char) is valid
1294 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(strlen(msg)+2);
1295 buffer[0] = '\1';
1296 strcpy(&buffer[1], msg);
1297 }
1298 }
1299
1300
1301 bool dlopen_preflight(const char* path)
1302 {
1303 if ( dyld::gLogAPIs )
1304 dyld::log("%s(%s)\n", __func__, path);
1305
1306 dlerrorClear();
1307
1308 bool result = false;
1309 std::vector<const char*> rpathsFromCallerImage;
1310 try {
1311 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1312 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1313 // for dlopen, use rpath from caller image and from main executable
1314 if ( callerImage != NULL )
1315 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1316 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
1317 if ( callerImage != dyld::mainExecutable() ) {
1318 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1319 }
1320
1321 ImageLoader* image = NULL;
1322 dyld::LoadContext context;
1323 context.useSearchPaths = true;
1324 context.useLdLibraryPath= (strchr(path, '/') == NULL); // a leafname implies should search
1325 context.implicitRPath = (path[0] != '/'); // a non-absolute path implies try rpath searching
1326 context.matchByInstallName = true;
1327 context.dontLoad = false;
1328 context.mustBeBundle = false;
1329 context.mustBeDylib = false;
1330 context.findDLL = false;
1331 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
1332 context.rpath = &callersRPaths; // rpaths from caller and main executable
1333
1334 image = load(path, context);
1335 if ( image != NULL ) {
1336 dyld::preflight(image, callersRPaths); // image object deleted by dyld::preflight()
1337 result = true;
1338 }
1339 }
1340 catch (const char* msg) {
1341 const char* str = dyld::mkstringf("dlopen_preflight(%s): %s", path, msg);
1342 dlerrorSet(str);
1343 free((void*)str);
1344 free((void*)msg); // our free() will do nothing if msg is a string literal
1345 }
1346 // free rpaths (getRPaths() malloc'ed each string)
1347 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
1348 const char* str = *it;
1349 free((void*)str);
1350 }
1351 return result;
1352 }
1353
1354
1355 void* dlopen(const char* path, int mode)
1356 {
1357 if ( dyld::gLogAPIs )
1358 dyld::log("%s(%s, 0x%08X)\n", __func__, ((path==NULL) ? "NULL" : path), mode);
1359
1360 dlerrorClear();
1361
1362 // passing NULL for path means return magic object
1363 if ( path == NULL ) {
1364 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1365 if ( (mode & RTLD_FIRST) != 0 )
1366 return RTLD_MAIN_ONLY;
1367 else
1368 return RTLD_DEFAULT;
1369 }
1370
1371 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1372 bool lockHeld = false;
1373 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 4) ) {
1374 dyld::gLibSystemHelpers->acquireGlobalDyldLock();
1375 lockHeld = true;
1376 }
1377
1378 void* result = NULL;
1379 ImageLoader* image = NULL;
1380 std::vector<const char*> rpathsFromCallerImage;
1381 try {
1382 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1383 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1384 // for dlopen, use rpath from caller image and from main executable
1385 if ( callerImage != NULL )
1386 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1387 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
1388 if ( callerImage != dyld::mainExecutable() ) {
1389 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1390 }
1391
1392 dyld::LoadContext context;
1393 context.useSearchPaths = true;
1394 context.useLdLibraryPath= (strchr(path, '/') == NULL); // a leafname implies should search
1395 context.implicitRPath = (path[0] != '/'); // a non-absolute path implies try rpath searching
1396 context.matchByInstallName = true;
1397 context.dontLoad = ( (mode & RTLD_NOLOAD) != 0 );
1398 context.mustBeBundle = false;
1399 context.mustBeDylib = false;
1400 context.findDLL = ( (mode & RTLD_DLL) != 0 );
1401 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
1402 context.rpath = &callersRPaths; // rpaths from caller and main executable
1403
1404 image = load(path, context);
1405 if ( image != NULL ) {
1406 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1407 // this image is not garbage collected
1408 image->incrementDlopenReferenceCount();
1409 // link in all dependents
1410 if ( (mode & RTLD_NOLOAD) == 0 ) {
1411 bool alreadyLinked = image->isLinked();
1412 bool forceLazysBound = ( (mode & RTLD_NOW) != 0 );
1413 dyld::link(image, forceLazysBound, callersRPaths);
1414 if ( ! alreadyLinked ) {
1415 // only hide exports if image is not already in use
1416 if ( (mode & RTLD_LOCAL) != 0 )
1417 image->setHideExports(true);
1418 }
1419 }
1420
1421 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1422 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1423 // The subtle differences are:
1424 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1425 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1426 if ( (mode & RTLD_NODELETE) != 0 )
1427 image->setLeaveMapped();
1428
1429 // release global dyld lock early, this enables initializers to do threaded operations
1430 if ( lockHeld ) {
1431 dyld::gLibSystemHelpers->releaseGlobalDyldLock();
1432 lockHeld = false;
1433 }
1434
1435 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1436 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1437 // called from within an initializer because it can cause initializers to run
1438 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1439 // to run, then don't use RTLD_NOLOAD.
1440 if ( (mode & RTLD_NOLOAD) == 0 ) {
1441 // run initializers
1442 dyld::runInitializers(image);
1443 }
1444
1445 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1446 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1447 if ( (mode & RTLD_FIRST) != 0 )
1448 result = (void*)(((uintptr_t)image)|1);
1449 else
1450 result = image;
1451 }
1452 }
1453 catch (const char* msg) {
1454 if ( image != NULL ) {
1455 // load() succeeded but, link() failed
1456 // back down reference count and do GC
1457 image->decrementDlopenReferenceCount();
1458 dyld::garbageCollectImages();
1459 }
1460 const char* str = dyld::mkstringf("dlopen(%s, %d): %s", path, mode, msg);
1461 dlerrorSet(str);
1462 free((void*)str);
1463 free((void*)msg); // our free() will do nothing if msg is a string literal
1464 result = NULL;
1465 }
1466 // free rpaths (getRPaths() malloc'ed each string)
1467 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
1468 const char* str = *it;
1469 free((void*)str);
1470 }
1471
1472 if ( lockHeld )
1473 dyld::gLibSystemHelpers->releaseGlobalDyldLock();
1474 return result;
1475 }
1476
1477
1478
1479 int dlclose(void* handle)
1480 {
1481 if ( dyld::gLogAPIs )
1482 dyld::log("%s(%p)\n", __func__, handle);
1483
1484 // silently accept magic handles for main executable
1485 if ( handle == RTLD_MAIN_ONLY )
1486 return 0;
1487 if ( handle == RTLD_DEFAULT )
1488 return 0;
1489
1490 ImageLoader* image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
1491 if ( dyld::validImage(image) ) {
1492 dlerrorClear();
1493 // decrement use count
1494 if ( image->decrementDlopenReferenceCount() ) {
1495 dlerrorSet("dlclose() called too many times");
1496 return -1;
1497 }
1498 // remove image if reference count went to zero
1499 dyld::garbageCollectImages();
1500 return 0;
1501 }
1502 else {
1503 dlerrorSet("invalid handle passed to dlclose()");
1504 return -1;
1505 }
1506 }
1507
1508
1509
1510 int dladdr(const void* address, Dl_info* info)
1511 {
1512 if ( dyld::gLogAPIs )
1513 dyld::log("%s(%p, %p)\n", __func__, address, info);
1514
1515 ImageLoader* image = dyld::findImageContainingAddress(address);
1516 if ( image != NULL ) {
1517 info->dli_fname = image->getLogicalPath();
1518 info->dli_fbase = (void*)image->machHeader();
1519 // find closest exported symbol in the image
1520 const uint32_t exportCount = image->getExportedSymbolCount();
1521 const ImageLoader::Symbol* bestSym = NULL;
1522 const void* bestAddr = 0;
1523 for(uint32_t i=0; i < exportCount; ++i) {
1524 const ImageLoader::Symbol* sym = image->getIndexedExportedSymbol(i);
1525 const void* symAddr = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
1526 if ( (symAddr <= address) && (bestAddr < symAddr) ) {
1527 bestSym = sym;
1528 bestAddr = symAddr;
1529 }
1530 }
1531 if ( bestSym != NULL ) {
1532 info->dli_sname = image->getExportedSymbolName(bestSym);
1533 if ( info->dli_sname[0] == '_' )
1534 info->dli_sname = info->dli_sname +1; // strip off leading underscore
1535 info->dli_saddr = (void*)bestAddr;
1536 }
1537 else {
1538 info->dli_sname = NULL;
1539 info->dli_saddr = NULL;
1540 }
1541 return 1; // success
1542 }
1543 return 0; // failure
1544 }
1545
1546
1547 char* dlerror()
1548 {
1549 if ( dyld::gLogAPIs )
1550 dyld::log("%s()\n", __func__);
1551
1552 if ( dyld::gLibSystemHelpers != NULL ) {
1553 // first char of buffer is flag whether string (starting at second char) is valid
1554 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
1555 if ( buffer[0] != '\0' ) { // if valid buffer
1556 buffer[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1557 return &buffer[1]; // return message
1558 }
1559 }
1560 return NULL;
1561 }
1562
1563 void* dlsym(void* handle, const char* symbolName)
1564 {
1565 if ( dyld::gLogAPIs )
1566 dyld::log("%s(%p, %s)\n", __func__, handle, symbolName);
1567
1568 dlerrorClear();
1569
1570 const ImageLoader* image;
1571 const ImageLoader::Symbol* sym;
1572
1573 // dlsym() assumes symbolName passed in is same as in C source code
1574 // dyld assumes all symbol names have an underscore prefix
1575 char underscoredName[strlen(symbolName)+2];
1576 underscoredName[0] = '_';
1577 strcpy(&underscoredName[1], symbolName);
1578
1579 // magic "search all" handle
1580 if ( handle == RTLD_DEFAULT ) {
1581 if ( dyld::flatFindExportedSymbol(underscoredName, &sym, &image) ) {
1582 return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
1583 }
1584 const char* str = dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName);
1585 dlerrorSet(str);
1586 free((void*)str);
1587 return NULL;
1588 }
1589
1590 // magic "search only main executable" handle
1591 if ( handle == RTLD_MAIN_ONLY ) {
1592 image = dyld::mainExecutable();
1593 sym = image->findExportedSymbol(underscoredName, NULL, true, &image); // search RTLD_FIRST way
1594 if ( sym != NULL ) {
1595 return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
1596 }
1597 const char* str = dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName);
1598 dlerrorSet(str);
1599 free((void*)str);
1600 return NULL;
1601 }
1602
1603 // magic "search what I would see" handle
1604 if ( handle == RTLD_NEXT ) {
1605 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1606 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1607 sym = callerImage->findExportedSymbolInDependentImages(underscoredName, dyld::gLinkContext, &image); // don't search image, but do search what it links against
1608 if ( sym != NULL ) {
1609 return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
1610 }
1611 const char* str = dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName);
1612 dlerrorSet(str);
1613 free((void*)str);
1614 return NULL;
1615 }
1616 // magic "search me, then what I would see" handle
1617 if ( handle == RTLD_SELF ) {
1618 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1619 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1620 sym = callerImage->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
1621 if ( sym != NULL ) {
1622 return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
1623 }
1624 const char* str = dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName);
1625 dlerrorSet(str);
1626 free((void*)str);
1627 return NULL;
1628 }
1629 // real handle
1630 image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
1631 if ( dyld::validImage(image) ) {
1632 if ( (((uintptr_t)handle) & 1) != 0 )
1633 sym = image->findExportedSymbol(underscoredName, NULL, true, &image); // search RTLD_FIRST way
1634 else
1635 sym = image->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
1636
1637 if ( sym != NULL ) {
1638 return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
1639 }
1640 const char* str = dyld::mkstringf("dlsym(%p, %s): symbol not found", handle, symbolName);
1641 dlerrorSet(str);
1642 free((void*)str);
1643 }
1644 else {
1645 dlerrorSet("invalid handle passed to dlsym()");
1646 }
1647 return NULL;
1648 }
1649
1650
1651
1652 void* dlord(void* handle, uint32_t ordinal)
1653 {
1654 if ( dyld::gLogAPIs )
1655 dyld::log("%s(%p, %u)\n", __func__, handle, ordinal);
1656
1657 dlerrorClear();
1658
1659
1660 // magic "search all" handle
1661 if ( handle == RTLD_DEFAULT ) {
1662 const char* str = dyld::mkstringf("dlord(RTLD_DEFAULT, %u): not supported", ordinal);
1663 dlerrorSet(str);
1664 free((void*)str);
1665 return NULL;
1666 }
1667 // magic "search only main executable" handle
1668 if ( handle == RTLD_MAIN_ONLY ) {
1669 const char* str = dyld::mkstringf("dlord(RTLD_MAIN_ONLY, %u): not supported", ordinal);
1670 dlerrorSet(str);
1671 free((void*)str);
1672 return NULL;
1673 }
1674 // magic "search what I would see" handle
1675 if ( handle == RTLD_NEXT ) {
1676 const char* str = dyld::mkstringf("dlord(RTLD_NEXT, %u): not supported", ordinal);
1677 dlerrorSet(str);
1678 free((void*)str);
1679 return NULL;
1680 }
1681 // magic "search me, then what I would see" handle
1682 if ( handle == RTLD_SELF ) {
1683 const char* str = dyld::mkstringf("dlord(RTLD_SELF, %u): not supported", ordinal);
1684 dlerrorSet(str);
1685 free((void*)str);
1686 return NULL;
1687 }
1688
1689 // real handle
1690 const ImageLoader* image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
1691 if ( dyld::validImage(image) ) {
1692 const ImageLoader::Symbol* sym;
1693 sym = image->getIndexedExportedSymbol(ordinal-1); // map ordinals to mach-o zero based index
1694
1695 if ( sym != NULL ) {
1696 return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
1697 }
1698 const char* str = dyld::mkstringf("dlord(%p, %u): ordinal not found", handle, ordinal);
1699 dlerrorSet(str);
1700 free((void*)str);
1701 }
1702 else {
1703 dlerrorSet("invalid handle passed to dlord()");
1704 }
1705 return NULL;
1706 }
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717 static const struct dyld_all_image_infos* _dyld_get_all_image_infos()
1718 {
1719 return &dyld_all_image_infos;
1720 }
1721
1722
1723
1724 void dyld_register_image_state_change_handler(dyld_image_states state, bool batch,
1725 dyld_image_state_change_handler handler)
1726 {
1727 if ( dyld::gLogAPIs )
1728 dyld::log("%s(%d, %d, %p)\n", __func__, state, batch, handler);
1729 if ( batch )
1730 dyld::registerImageStateBatchChangeHandler(state, handler);
1731 else
1732 dyld::registerImageStateSingleChangeHandler(state, handler);
1733 }
1734
1735
1736
1737
1738
1739
1740
1741