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