]> git.saurik.com Git - apple/dyld.git/blob - src/dyldAPIs.cpp
dyld-519.2.2.tar.gz
[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 "ImageLoaderMachO.h"
55 #include "dyld.h"
56 #include "dyldLibSystemInterface.h"
57 #include "DyldSharedCache.h"
58
59 #undef _POSIX_C_SOURCE
60 #include "dlfcn.h"
61
62
63 // this was in dyld_priv.h but it is no longer exported
64 extern "C" {
65 const struct dyld_all_image_infos* _dyld_get_all_image_infos();
66 }
67
68 // from dyldExceptions.c
69 extern "C" void __Unwind_SjLj_SetThreadKey(pthread_key_t key);
70
71 // from dyld_gdb.cpp
72 extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
73 extern uint32_t allImagesCount();
74 extern const mach_header* allImagesIndexedMachHeader(uint32_t index);
75 extern const char* allImagesIndexedPath(uint32_t index);
76
77 extern "C" int _dyld_func_lookup(const char* name, void** address);
78
79 // deprecated APIs are still availble on Mac OS X, but not on iPhone OS
80 #if __IPHONE_OS_VERSION_MIN_REQUIRED
81 #define DEPRECATED_APIS_SUPPORTED 0
82 #else
83 #define DEPRECATED_APIS_SUPPORTED 1
84 #endif
85
86 static bool sDynamicInterposing = false;
87
88 #if DEPRECATED_APIS_SUPPORTED
89 static char sLastErrorFilePath[1024];
90 static NSLinkEditErrors sLastErrorFileCode;
91 static int sLastErrorNo;
92 #endif
93
94 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
95 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
96 // This conditional keeps support for old libSystem's which needed some help implementing the API's
97 #define OLD_LIBSYSTEM_SUPPORT (__i386__)
98
99 // The following functions have no prototype in any header. They are special cases
100 // where _dyld_func_lookup() is used directly.
101 static void _dyld_make_delayed_module_initializer_calls();
102 static void registerThreadHelpers(const dyld::LibSystemHelpers*);
103 #if DEPRECATED_APIS_SUPPORTED
104 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit);
105 #if OLD_LIBSYSTEM_SUPPORT
106 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options);
107 #endif
108 static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions);
109 static bool NSMakePrivateModulePublic(NSModule module);
110 static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header);
111
112 // The following functions are dyld API's, but since dyld links with a static copy of libc.a
113 // the public name cannot be used.
114 static void client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module);
115 static bool client_NSIsSymbolNameDefined(const char* symbolName);
116 #endif // DEPRECATED_APIS_SUPPORTED
117 #if SUPPORT_ZERO_COST_EXCEPTIONS
118 static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info);
119 #endif
120 #if DEPRECATED_APIS_SUPPORTED
121 #endif
122
123 static void unimplemented()
124 {
125 dyld::halt("unimplemented dyld function\n");
126 }
127
128 struct dyld_func {
129 const char* name;
130 void* implementation;
131 };
132
133 static struct dyld_func dyld_funcs[] = {
134 {"__dyld_register_func_for_add_image", (void*)_dyld_register_func_for_add_image },
135 {"__dyld_register_func_for_remove_image", (void*)_dyld_register_func_for_remove_image },
136 {"__dyld_dladdr", (void*)dladdr },
137 {"__dyld_dlclose", (void*)dlclose },
138 {"__dyld_dlerror", (void*)dlerror },
139 {"__dyld_dlopen", (void*)dlopen },
140 {"__dyld_dlsym", (void*)dlsym },
141 {"__dyld_dlopen_preflight", (void*)dlopen_preflight },
142 {"__dyld_image_count", (void*)_dyld_image_count },
143 {"__dyld_get_image_header", (void*)_dyld_get_image_header },
144 {"__dyld_get_image_vmaddr_slide", (void*)_dyld_get_image_vmaddr_slide },
145 {"__dyld_get_image_name", (void*)_dyld_get_image_name },
146 {"__dyld_get_image_slide", (void*)_dyld_get_image_slide },
147 {"__dyld__NSGetExecutablePath", (void*)_NSGetExecutablePath },
148
149 // SPIs
150 {"__dyld_register_thread_helpers", (void*)registerThreadHelpers },
151 {"__dyld_fork_child", (void*)_dyld_fork_child },
152 {"__dyld_make_delayed_module_initializer_calls", (void*)_dyld_make_delayed_module_initializer_calls },
153 {"__dyld_get_all_image_infos", (void*)_dyld_get_all_image_infos },
154 #if SUPPORT_ZERO_COST_EXCEPTIONS
155 {"__dyld_find_unwind_sections", (void*)client_dyld_find_unwind_sections },
156 #endif
157 #if __i386__ || __x86_64__ || __arm__ || __arm64__
158 {"__dyld_fast_stub_entry", (void*)dyld::fastBindLazySymbol },
159 #endif
160 {"__dyld_image_path_containing_address", (void*)dyld_image_path_containing_address },
161 {"__dyld_shared_cache_some_image_overridden", (void*)dyld_shared_cache_some_image_overridden },
162 {"__dyld_process_is_restricted", (void*)dyld::processIsRestricted },
163 {"__dyld_dynamic_interpose", (void*)dyld_dynamic_interpose },
164 {"__dyld_shared_cache_file_path", (void*)dyld::getStandardSharedCacheFilePath },
165 {"__dyld_get_image_header_containing_address", (void*)dyld_image_header_containing_address },
166 {"__dyld_is_memory_immutable", (void*)_dyld_is_memory_immutable },
167 {"__dyld_objc_notify_register", (void*)_dyld_objc_notify_register },
168 {"__dyld_get_shared_cache_uuid", (void*)_dyld_get_shared_cache_uuid },
169 {"__dyld_get_shared_cache_range", (void*)_dyld_get_shared_cache_range },
170
171
172 // deprecated
173 #if DEPRECATED_APIS_SUPPORTED
174 {"__dyld_lookup_and_bind", (void*)client_dyld_lookup_and_bind },
175 {"__dyld_lookup_and_bind_with_hint", (void*)_dyld_lookup_and_bind_with_hint },
176 {"__dyld_lookup_and_bind_fully", (void*)_dyld_lookup_and_bind_fully },
177 {"__dyld_install_handlers", (void*)_dyld_install_handlers },
178 {"__dyld_link_edit_error", (void*)NSLinkEditError },
179 {"__dyld_unlink_module", (void*)NSUnLinkModule },
180 {"__dyld_bind_fully_image_containing_address", (void*)_dyld_bind_fully_image_containing_address },
181 {"__dyld_image_containing_address", (void*)_dyld_image_containing_address },
182 {"__dyld_register_binding_handler", (void*)_dyld_register_binding_handler },
183 {"__dyld_NSNameOfSymbol", (void*)NSNameOfSymbol },
184 {"__dyld_NSAddressOfSymbol", (void*)NSAddressOfSymbol },
185 {"__dyld_NSModuleForSymbol", (void*)NSModuleForSymbol },
186 {"__dyld_NSLookupAndBindSymbol", (void*)NSLookupAndBindSymbol },
187 {"__dyld_NSLookupAndBindSymbolWithHint", (void*)NSLookupAndBindSymbolWithHint },
188 {"__dyld_NSLookupSymbolInModule", (void*)NSLookupSymbolInModule},
189 {"__dyld_NSLookupSymbolInImage", (void*)NSLookupSymbolInImage},
190 {"__dyld_NSMakePrivateModulePublic", (void*)NSMakePrivateModulePublic},
191 {"__dyld_NSIsSymbolNameDefined", (void*)client_NSIsSymbolNameDefined},
192 {"__dyld_NSIsSymbolNameDefinedWithHint", (void*)NSIsSymbolNameDefinedWithHint },
193 {"__dyld_NSIsSymbolNameDefinedInImage", (void*)NSIsSymbolNameDefinedInImage},
194 {"__dyld_NSNameOfModule", (void*)NSNameOfModule },
195 {"__dyld_NSLibraryNameForModule", (void*)NSLibraryNameForModule },
196 {"__dyld_NSAddLibrary", (void*)NSAddLibrary },
197 {"__dyld_NSAddLibraryWithSearching", (void*)NSAddLibraryWithSearching },
198 {"__dyld_NSAddImage", (void*)NSAddImage },
199 {"__dyld_launched_prebound", (void*)_dyld_launched_prebound },
200 {"__dyld_all_twolevel_modules_prebound", (void*)_dyld_all_twolevel_modules_prebound },
201 {"__dyld_call_module_initializers_for_dylib", (void*)_dyld_call_module_initializers_for_dylib },
202 {"__dyld_NSCreateObjectFileImageFromFile", (void*)NSCreateObjectFileImageFromFile },
203 {"__dyld_NSCreateObjectFileImageFromMemory", (void*)NSCreateObjectFileImageFromMemory },
204 {"__dyld_NSDestroyObjectFileImage", (void*)NSDestroyObjectFileImage },
205 {"__dyld_NSLinkModule", (void*)NSLinkModule },
206 {"__dyld_NSSymbolDefinitionCountInObjectFileImage", (void*)NSSymbolDefinitionCountInObjectFileImage },
207 {"__dyld_NSSymbolDefinitionNameInObjectFileImage", (void*)NSSymbolDefinitionNameInObjectFileImage },
208 {"__dyld_NSIsSymbolDefinedInObjectFileImage", (void*)NSIsSymbolDefinedInObjectFileImage },
209 {"__dyld_NSSymbolReferenceNameInObjectFileImage", (void*)NSSymbolReferenceNameInObjectFileImage },
210 {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage },
211 {"__dyld_NSGetSectionDataInObjectFileImage", (void*)NSGetSectionDataInObjectFileImage },
212 #if OLD_LIBSYSTEM_SUPPORT
213 {"__dyld_link_module", (void*)_dyld_link_module },
214 #endif
215 #endif //DEPRECATED_APIS_SUPPORTED
216
217 {NULL, 0}
218 };
219
220
221
222 #if DEPRECATED_APIS_SUPPORTED
223
224 static void dyldAPIhalt(const char* apiName, const char* errorMsg)
225 {
226 dyld::log("dyld: %s() error\n", apiName);
227 dyld::halt(errorMsg);
228 }
229
230 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
231 inline NSSymbol SymbolToNSSymbol(const ImageLoader::Symbol* sym)
232 {
233 return (NSSymbol)sym;
234 }
235 inline const ImageLoader::Symbol* NSSymbolToSymbol(NSSymbol sym)
236 {
237 return (const ImageLoader::Symbol*)sym;
238 }
239
240 // dyld's abstract type NSModule is implemented as ImageLoader*
241 inline NSModule ImageLoaderToNSModule(const ImageLoader* image)
242 {
243 return (NSModule)image;
244 }
245 inline ImageLoader* NSModuleToImageLoader(NSModule module)
246 {
247 ImageLoader* image = (ImageLoader*)module;
248 if ( dyld::validImage(image) )
249 return image;
250 return NULL;
251 }
252
253 // actual definition for opaque type
254 struct __NSObjectFileImage
255 {
256 ImageLoader* image;
257 const void* imageBaseAddress; // not used with OFI created from files
258 size_t imageLength; // not used with OFI created from files
259 };
260
261
262 VECTOR_NEVER_DESTRUCTED(NSObjectFileImage);
263 static std::vector<NSObjectFileImage> sObjectFileImages;
264
265
266
267 //
268 // __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
269 // The contained image is delete in one of two places:
270 // NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
271 // NSDestroyObjectFileImage deletes the image if image is not in list of valid images
272 //
273
274
275
276 static void setLastError(NSLinkEditErrors code, int errnum, const char* file, const char* message)
277 {
278 dyld::setErrorMessage(message);
279 strncpy(sLastErrorFilePath, file, 1024);
280 sLastErrorFilePath[1023] = '\0';
281 sLastErrorFileCode = code;
282 sLastErrorNo = errnum;
283 }
284
285 #endif // DEPRECATED_APIS_SUPPORTED
286
287 /*
288 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
289 * copies the path of the executable into the buffer and returns 0 if the path
290 * was successfully copied in the provided buffer. If the buffer is not large
291 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
292 * Note that _NSGetExecutablePath will return "a path" to the executable not a
293 * "real path" to the executable. That is the path may be a symbolic link and
294 * not the real file. And with deep directories the total bufsize needed could
295 * be more than MAXPATHLEN.
296 */
297 int _NSGetExecutablePath(char* buf, uint32_t *bufsize)
298 {
299 if ( dyld::gLogAPIs )
300 dyld::log("%s(...)\n", __func__);
301 const char* exePath = dyld::getExecutablePath();
302 if(*bufsize < strlen(exePath) + 1){
303 *bufsize = (uint32_t)(strlen(exePath) + 1);
304 return -1;
305 }
306 strcpy(buf, exePath);
307 return 0;
308 }
309
310 uint32_t _dyld_image_count(void)
311 {
312 if ( dyld::gLogAPIs )
313 dyld::log("%s()\n", __func__);
314 return allImagesCount();
315 }
316
317 const struct mach_header* _dyld_get_image_header(uint32_t image_index)
318 {
319 if ( dyld::gLogAPIs )
320 dyld::log("%s(%u)\n", __func__, image_index);
321 return allImagesIndexedMachHeader(image_index);
322 }
323
324 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index)
325 {
326 if ( dyld::gLogAPIs )
327 dyld::log("%s(%u)\n", __func__, image_index);
328 const struct mach_header* mh = allImagesIndexedMachHeader(image_index);
329 if ( mh != NULL )
330 return ImageLoaderMachO::computeSlide(mh);
331 else
332 return 0;
333 }
334
335 intptr_t _dyld_get_image_slide(const struct mach_header* mh)
336 {
337 if ( dyld::gLogAPIs )
338 dyld::log("%s(%p)\n", __func__, mh);
339 return ImageLoaderMachO::computeSlide(mh);
340 }
341
342
343 const char* _dyld_get_image_name(uint32_t image_index)
344 {
345 if ( dyld::gLogAPIs )
346 dyld::log("%s(%u)\n", __func__, image_index);
347 return allImagesIndexedPath(image_index);
348 }
349
350 const struct mach_header * dyld_image_header_containing_address(const void* address)
351 {
352 if ( dyld::gLogAPIs )
353 dyld::log("%s(%p)\n", __func__, address);
354 #if SUPPORT_ACCELERATE_TABLES
355 const mach_header* mh;
356 const char* path;
357 if ( dyld::addressInCache(address, &mh, &path) )
358 return mh;
359 #endif
360 ImageLoader* image = dyld::findImageContainingAddress(address);
361 if ( image != NULL )
362 return image->machHeader();
363 return NULL;
364 }
365
366
367 void _dyld_register_func_for_add_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
368 {
369 if ( dyld::gLogAPIs )
370 dyld::log("%s(%p)\n", __func__, (void *)func);
371 dyld::registerAddCallback(func);
372 }
373
374 void _dyld_register_func_for_remove_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
375 {
376 if ( dyld::gLogAPIs )
377 dyld::log("%s(%p)\n", __func__, (void *)func);
378 dyld::registerRemoveCallback(func);
379 }
380
381
382
383 // called by crt before main() by programs linked with 10.4 or earlier crt1.o
384 static void _dyld_make_delayed_module_initializer_calls()
385 {
386 if ( dyld::gLogAPIs )
387 dyld::log("%s()\n", __func__);
388
389 #if SUPPORT_OLD_CRT_INITIALIZATION
390 if ( dyld::gRunInitializersOldWay )
391 dyld::initializeMainExecutable();
392 #endif
393 }
394
395
396
397 #if DEPRECATED_APIS_SUPPORTED
398
399 //
400 // _dyld_call_module_initializers_for_dylib() is the dyld side of
401 // __initialize_Cplusplus() which is in dylib1.o.
402 // It is intended to only be called inside -init rouintes.
403 // -init routines are called before module initializers (what C++
404 // initializers use). Calling __initialize_Cplusplus() in a -init
405 // routine causes the module initializers for an image to be called
406 // which then allows C++ to be used inside a -init routine
407 //
408 static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header)
409 {
410 if ( dyld::gLogAPIs )
411 dyld::log("__initialize_Cplusplus()\n");
412
413 // for now, do nothing...
414 }
415
416
417 void _dyld_lookup_and_bind_fully(const char* symbolName, void** address, NSModule* module)
418 {
419 if ( dyld::gLogAPIs )
420 dyld::log("%s(\"%s\", %p, %p)\n", __func__, symbolName, address, module);
421 ImageLoader* image;
422 const ImageLoader::Symbol* sym;
423 dyld::clearErrorMessage();
424 if ( dyld::flatFindExportedSymbol(symbolName, &sym, (const ImageLoader**)&image) ) {
425 try {
426 image->bindAllLazyPointers(dyld::gLinkContext, true);
427 if ( address != NULL)
428 *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
429 if ( module != NULL)
430 *module = ImageLoaderToNSModule(image);
431 }
432 catch (const char* msg) {
433 dyldAPIhalt(__func__, msg);
434 }
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 // Note: This cannot have public name because dyld is built with a static copy of libc.a
446 // which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
447 static void client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module)
448 {
449 if ( dyld::gLogAPIs )
450 dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName, address, module);
451 const ImageLoader* image;
452 const ImageLoader::Symbol* sym;
453 if ( 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 void _dyld_lookup_and_bind_with_hint(const char* symbolName, const char* library_name_hint, void** address, NSModule* module)
469 {
470 if ( dyld::gLogAPIs )
471 dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__, symbolName, library_name_hint, address, module);
472 const ImageLoader* image;
473 const ImageLoader::Symbol* sym;
474 // Look for library whose path contains the hint. If that fails search everywhere
475 if ( dyld::flatFindExportedSymbolWithHint(symbolName, library_name_hint, &sym, &image)
476 || dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
477 if ( address != NULL)
478 *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
479 if ( module != NULL)
480 *module = ImageLoaderToNSModule(image);
481 }
482 else {
483 // on failure to find symbol return NULLs
484 if ( address != NULL)
485 *address = NULL;
486 if ( module != NULL)
487 *module = NULL;
488 }
489 }
490
491
492 NSSymbol NSLookupAndBindSymbol(const char *symbolName)
493 {
494 if ( dyld::gLogAPIs )
495 dyld::log("%s(\"%s\")\n", __func__, symbolName);
496 const ImageLoader* image;
497 const ImageLoader::Symbol* sym;
498 if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
499 return SymbolToNSSymbol(sym);
500 }
501 // return NULL on failure
502 return NULL;
503 }
504
505 NSSymbol NSLookupAndBindSymbolWithHint(const char* symbolName, const char* libraryNameHint)
506 {
507 if ( dyld::gLogAPIs )
508 dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
509 const ImageLoader* image;
510 const ImageLoader::Symbol* sym;
511 bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
512 if ( ! found ) {
513 // hint failed, do slow search of all images
514 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
515 }
516 if ( found )
517 return SymbolToNSSymbol(sym);
518
519 // return NULL on failure and log
520 if ( dyld::gLogAPIs )
521 dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__, symbolName, libraryNameHint);
522 return NULL;
523 }
524
525
526
527
528 static __attribute__((noinline))
529 const struct mach_header* addImage(void* callerAddress, const char* path, bool search, bool dontLoad, bool matchInstallName, bool abortOnError)
530 {
531 ImageLoader* image = NULL;
532 std::vector<const char*> rpathsFromCallerImage;
533 try {
534 dyld::clearErrorMessage();
535 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
536 // like dlopen, use rpath from caller image and from main executable
537 if ( callerImage != NULL )
538 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
539 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
540 if ( callerImage != dyld::mainExecutable() ) {
541 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
542 }
543 dyld::LoadContext context;
544 context.useSearchPaths = search;
545 context.useFallbackPaths = search;
546 context.useLdLibraryPath = false;
547 context.implicitRPath = false;
548 context.matchByInstallName = matchInstallName;
549 context.dontLoad = dontLoad;
550 context.mustBeBundle = false;
551 context.mustBeDylib = true;
552 context.canBePIE = false;
553 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
554 context.rpath = &callersRPaths; // rpaths from caller and main executable
555
556 unsigned cacheIndex;
557 image = load(path, context, cacheIndex);
558 if ( image != NULL ) {
559 if ( context.matchByInstallName )
560 image->setMatchInstallPath(true);
561 dyld::link(image, false, false, callersRPaths, cacheIndex);
562 dyld::runInitializers(image);
563 // images added with NSAddImage() can never be unloaded
564 image->setNeverUnload();
565 }
566 }
567 catch (const char* msg) {
568 dyld::garbageCollectImages();
569 if ( abortOnError) {
570 char pathMsg[strlen(msg)+strlen(path)+4];
571 strcpy(pathMsg, msg);
572 strcat(pathMsg, " ");
573 strcat(pathMsg, path);
574 dyldAPIhalt("NSAddImage", pathMsg);
575 }
576 // not halting, so set error state for NSLinkEditError to find
577 setLastError(NSLinkEditOtherError, 0, path, msg);
578 free((void*)msg); // our free() will do nothing if msg is a string literal
579 image = NULL;
580 }
581 // free rpaths (getRPaths() malloc'ed each string)
582 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
583 const char* str = *it;
584 free((void*)str);
585 }
586 if ( image == NULL )
587 return NULL;
588 else
589 return image->machHeader();
590 }
591
592
593 const struct mach_header* NSAddImage(const char* path, uint32_t options)
594 {
595 if ( dyld::gLogAPIs )
596 dyld::log("%s(\"%s\", 0x%08X)\n", __func__, path, options);
597 const bool dontLoad = ( (options & NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED) != 0 );
598 const bool search = ( (options & NSADDIMAGE_OPTION_WITH_SEARCHING) != 0 );
599 const bool matchInstallName = ( (options & NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME) != 0 );
600 const bool abortOnError = ( (options & (NSADDIMAGE_OPTION_RETURN_ON_ERROR|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED)) == 0 );
601 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
602 return addImage(callerAddress, path, search, dontLoad, matchInstallName, abortOnError);
603 }
604
605 bool NSAddLibrary(const char* path)
606 {
607 if ( dyld::gLogAPIs )
608 dyld::log("%s(\"%s\")\n", __func__, path);
609 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
610 return (addImage(callerAddress, path, false, false, false, false) != NULL);
611 }
612
613 bool NSAddLibraryWithSearching(const char* path)
614 {
615 if ( dyld::gLogAPIs )
616 dyld::log("%s(\"%s\")\n", __func__, path);
617 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
618 return (addImage(callerAddress, path, true, false, false, false) != NULL);
619 }
620
621
622
623 //#define NSADDIMAGE_OPTION_NONE 0x0
624 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
625 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
626
627 bool NSIsSymbolNameDefinedInImage(const struct mach_header* mh, const char* symbolName)
628 {
629 if ( dyld::gLogAPIs )
630 dyld::log("%s(%p, \"%s\")\n", __func__, (void *)mh, symbolName);
631 ImageLoader* image = dyld::findImageByMachHeader(mh);
632 if ( image != NULL ) {
633 if ( image->findExportedSymbol(symbolName, true, NULL) != NULL)
634 return true;
635 }
636 return false;
637 }
638
639
640 NSSymbol NSLookupSymbolInImage(const struct mach_header* mh, const char* symbolName, uint32_t options)
641 {
642 if ( dyld::gLogAPIs )
643 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, mh, symbolName, options);
644 const ImageLoader::Symbol* symbol = NULL;
645 dyld::clearErrorMessage();
646 ImageLoader* image = dyld::findImageByMachHeader(mh);
647 if ( image != NULL ) {
648 try {
649 if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY ) {
650 image->bindAllLazyPointers(dyld::gLinkContext, true);
651 }
652 else if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW ) {
653 image->bindAllLazyPointers(dyld::gLinkContext, false);
654 }
655 }
656 catch (const char* msg) {
657 if ( (options & NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR) == 0 ) {
658 dyldAPIhalt(__func__, msg);
659 }
660 }
661 symbol = image->findExportedSymbol(symbolName, true, NULL);
662 }
663 if ( dyld::gLogAPIs && (symbol == NULL) )
664 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__, mh, symbolName, options);
665 return SymbolToNSSymbol(symbol);
666 }
667
668
669 // Note: This cannot have public name because dyld is built with a static copy of libc.a
670 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
671 static bool client_NSIsSymbolNameDefined(const char* symbolName)
672 {
673 if ( dyld::gLogAPIs )
674 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName);
675 const ImageLoader* image;
676 const ImageLoader::Symbol* sym;
677 return dyld::flatFindExportedSymbol(symbolName, &sym, &image);
678 }
679
680 bool NSIsSymbolNameDefinedWithHint(const char* symbolName, const char* libraryNameHint)
681 {
682 if ( dyld::gLogAPIs )
683 dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
684 const ImageLoader* image;
685 const ImageLoader::Symbol* sym;
686 bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
687 if ( ! found ) {
688 // hint failed, do slow search of all images
689 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
690 }
691 if ( !found && dyld::gLogAPIs )
692 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__, symbolName, libraryNameHint);
693 return found;
694 }
695
696 const char* NSNameOfSymbol(NSSymbol symbol)
697 {
698 if ( dyld::gLogAPIs )
699 dyld::log("%s(%p)\n", __func__, (void *)symbol);
700 const char* result = NULL;
701 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
702 if ( image != NULL )
703 result = image->getExportedSymbolName(NSSymbolToSymbol(symbol));
704 return result;
705 }
706
707 void* NSAddressOfSymbol(NSSymbol symbol)
708 {
709 if ( dyld::gLogAPIs )
710 dyld::log("%s(%p)\n", __func__, (void *)symbol);
711 if ( symbol == NULL )
712 return NULL;
713 void* result = NULL;
714 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
715 if ( image != NULL )
716 result = (void*)image->getExportedSymbolAddress(NSSymbolToSymbol(symbol), dyld::gLinkContext);
717 return result;
718 }
719
720 NSModule NSModuleForSymbol(NSSymbol symbol)
721 {
722 if ( dyld::gLogAPIs )
723 dyld::log("%s(%p)\n", __func__, (void *)symbol);
724 NSModule result = NULL;
725 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
726 if ( image != NULL )
727 result = ImageLoaderToNSModule(image);
728 return result;
729 }
730
731
732
733
734 bool _dyld_all_twolevel_modules_prebound(void)
735 {
736 if ( dyld::gLogAPIs )
737 dyld::log("%s()\n", __func__);
738 return FALSE;
739 }
740
741 bool _dyld_bind_fully_image_containing_address(const void* address)
742 {
743 if ( dyld::gLogAPIs )
744 dyld::log("%s(%p)\n", __func__, address);
745 dyld::clearErrorMessage();
746 ImageLoader* image = dyld::findImageContainingAddress(address);
747 if ( image != NULL ) {
748 try {
749 image->bindAllLazyPointers(dyld::gLinkContext, true);
750 return true;
751 }
752 catch (const char* msg) {
753 dyldAPIhalt(__func__, msg);
754 }
755 }
756 return false;
757 }
758
759 bool _dyld_image_containing_address(const void* address)
760 {
761 if ( dyld::gLogAPIs )
762 dyld::log("%s(%p)\n", __func__, address);
763 ImageLoader *imageLoader = dyld::findImageContainingAddress(address);
764 return (NULL != imageLoader);
765 }
766
767 static NSObjectFileImage createObjectImageFile(ImageLoader* image, const void* address = NULL, size_t len=0)
768 {
769 NSObjectFileImage result = new __NSObjectFileImage();
770 result->image = image;
771 result->imageBaseAddress = address;
772 result->imageLength = len;
773 sObjectFileImages.push_back(result);
774 return result;
775 }
776
777 NSObjectFileImageReturnCode NSCreateObjectFileImageFromFile(const char* pathName, NSObjectFileImage *objectFileImage)
778 {
779 if ( dyld::gLogAPIs )
780 dyld::log("%s(\"%s\", ...)\n", __func__, pathName);
781 try {
782 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
783 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
784
785 dyld::LoadContext context;
786 context.useSearchPaths = false;
787 context.useFallbackPaths = false;
788 context.useLdLibraryPath = false;
789 context.implicitRPath = false;
790 context.matchByInstallName = false;
791 context.dontLoad = false;
792 context.mustBeBundle = true;
793 context.mustBeDylib = false;
794 context.canBePIE = false;
795 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
796 context.rpath = NULL; // support not yet implemented
797
798 unsigned cacheIndex;
799 ImageLoader* image = dyld::load(pathName, context, cacheIndex);
800 // Note: We DO NOT link the image! NSLinkModule will do that
801 if ( image != NULL ) {
802 if ( !image->isBundle() ) {
803 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
804 return NSObjectFileImageInappropriateFile;
805 }
806 *objectFileImage = createObjectImageFile(image);
807 return NSObjectFileImageSuccess;
808 }
809 }
810 catch (const char* msg) {
811 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
812 dyld::garbageCollectImages();
813 free((void*)msg);
814 return NSObjectFileImageInappropriateFile;
815 }
816 return NSObjectFileImageFailure;
817 }
818
819
820 NSObjectFileImageReturnCode NSCreateObjectFileImageFromMemory(const void* address, size_t size, NSObjectFileImage *objectFileImage)
821 {
822 if ( dyld::gLogAPIs )
823 dyld::log("%s(%p, %lu, %p)\n", __func__, address, size, objectFileImage);
824
825 try {
826 ImageLoader* image = dyld::loadFromMemory((const uint8_t*)address, size, NULL);
827 if ( ! image->isBundle() ) {
828 // this API can only be used with bundles...
829 dyld::garbageCollectImages();
830 return NSObjectFileImageInappropriateFile;
831 }
832 // Note: We DO NOT link the image! NSLinkModule will do that
833 if ( image != NULL ) {
834 *objectFileImage = createObjectImageFile(image, address, size);
835 return NSObjectFileImageSuccess;
836 }
837 }
838 catch (const char* msg) {
839 free((void*)msg);
840 dyld::garbageCollectImages();
841 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
842 }
843 return NSObjectFileImageFailure;
844 }
845
846 static bool validOFI(NSObjectFileImage objectFileImage)
847 {
848 const size_t ofiCount = sObjectFileImages.size();
849 for (size_t i=0; i < ofiCount; ++i) {
850 if ( sObjectFileImages[i] == objectFileImage )
851 return true;
852 }
853 return false;
854 }
855
856 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage)
857 {
858 if ( dyld::gLogAPIs )
859 dyld::log("%s(%p)\n", __func__, objectFileImage);
860
861 if ( validOFI(objectFileImage) ) {
862 // a failure during NSLinkModule will delete the image
863 if ( objectFileImage->image != NULL ) {
864 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
865 // and we should delete it
866 bool linkedImage = dyld::validImage(objectFileImage->image);
867 if ( ! linkedImage ) {
868 ImageLoader::deleteImage(objectFileImage->image);
869 objectFileImage->image = NULL;
870 }
871 }
872
873 // remove from list of ofi's
874 for (std::vector<NSObjectFileImage>::iterator it=sObjectFileImages.begin(); it != sObjectFileImages.end(); it++) {
875 if ( *it == objectFileImage ) {
876 sObjectFileImages.erase(it);
877 break;
878 }
879 }
880
881 // if object was created from a memory, release that memory
882 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
883 if ( objectFileImage->imageBaseAddress != NULL ) {
884 bool freed = false;
885 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 6) ) {
886 size_t sz = (*dyld::gLibSystemHelpers->malloc_size)(objectFileImage->imageBaseAddress);
887 if ( sz != 0 ) {
888 (*dyld::gLibSystemHelpers->free)((void*)(objectFileImage->imageBaseAddress));
889 freed = true;
890 }
891 }
892 if ( ! freed )
893 vm_deallocate(mach_task_self(), (vm_address_t)objectFileImage->imageBaseAddress, objectFileImage->imageLength);
894 }
895
896 // free ofi object
897 delete objectFileImage;
898
899 return true;
900 }
901 return false;
902 }
903
904 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage)
905 {
906 if ( dyld::gLogAPIs )
907 dyld::log("%s(%p)\n", __func__, objectFileImage);
908 return objectFileImage->image->getExportedSymbolCount();
909 }
910
911 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal)
912 {
913 if ( dyld::gLogAPIs )
914 dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
915 const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedExportedSymbol(ordinal);
916 return objectFileImage->image->getExportedSymbolName(sym);
917 }
918
919 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage)
920 {
921 if ( dyld::gLogAPIs )
922 dyld::log("%s(%p)\n", __func__, objectFileImage);
923 return objectFileImage->image->getImportedSymbolCount();
924 }
925
926 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal,
927 bool* tentative_definition)
928 {
929 if ( dyld::gLogAPIs )
930 dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
931 const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedImportedSymbol(ordinal);
932 if ( tentative_definition != NULL ) {
933 ImageLoader::ReferenceFlags flags = objectFileImage->image->getImportedSymbolInfo(sym);
934 if ( (flags & ImageLoader::kTentativeDefinition) != 0 )
935 *tentative_definition = true;
936 else
937 *tentative_definition = false;
938 }
939 return objectFileImage->image->getImportedSymbolName(sym);
940 }
941
942 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage,
943 const char* segmentName, const char* sectionName, unsigned long* size)
944 {
945 if ( dyld::gLogAPIs )
946 dyld::log("%s(%p,%s, %s)\n", __func__, objectFileImage, segmentName, sectionName);
947
948 void* start;
949 size_t length;
950 if ( objectFileImage->image->getSectionContent(segmentName, sectionName, &start, &length) ) {
951 if ( size != NULL )
952 *size = length;
953 return start;
954 }
955 return NULL;
956 }
957
958
959
960 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage, const char* symbolName)
961 {
962 if ( dyld::gLogAPIs )
963 dyld::log("%s(%p,%s)\n", __func__, objectFileImage, symbolName);
964 const ImageLoader::Symbol* sym = objectFileImage->image->findExportedSymbol(symbolName, true, NULL);
965 return ( sym != NULL );
966 }
967
968
969
970 NSModule NSLinkModule(NSObjectFileImage objectFileImage, const char* moduleName, uint32_t options)
971 {
972 if ( dyld::gLogAPIs )
973 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, objectFileImage, moduleName, options);
974
975 dyld::clearErrorMessage();
976 try {
977 if ( (options & NSLINKMODULE_OPTION_CAN_UNLOAD) != 0 )
978 objectFileImage->image->setCanUnload();
979
980 // NSLinkModule allows a bundle to be link multpile times
981 // each link causes the bundle to be copied to a new address
982 if ( objectFileImage->image->isLinked() ) {
983 // already linked, so clone a new one and link it
984 objectFileImage->image = dyld::cloneImage(objectFileImage->image);
985 }
986
987 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
988 if ( objectFileImage->image->getPath() == NULL ) {
989 objectFileImage->image->setPath(moduleName);
990 // <rdar://problem/8812589> dyld has NULL paths in image info array
991 dyld_image_info info;
992 info.imageLoadAddress = objectFileImage->image->machHeader();
993 info.imageFilePath = moduleName;
994 info.imageFileModDate = 0;
995 addImagesToAllImages(1, &info);
996 }
997
998 // support private bundles
999 if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
1000 objectFileImage->image->setHideExports();
1001
1002 // set up linking options
1003 bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
1004
1005 // load libraries, rebase, bind, to make this image usable
1006 dyld::link(objectFileImage->image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL), UINT32_MAX);
1007
1008 // bump reference count to keep this bundle from being garbage collected
1009 objectFileImage->image->incrementDlopenReferenceCount();
1010
1011 // run initializers unless magic flag says not to
1012 if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
1013 dyld::runInitializers(objectFileImage->image);
1014
1015 return ImageLoaderToNSModule(objectFileImage->image);
1016 }
1017 catch (const char* msg) {
1018 dyld::garbageCollectImages();
1019 if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
1020 dyldAPIhalt(__func__, msg);
1021 // not halting, so set error state for NSLinkEditError to find
1022 setLastError(NSLinkEditOtherError, 0, moduleName, msg);
1023 // dyld::link() deleted the image so lose our reference
1024 objectFileImage->image = NULL;
1025 free((void*)msg);
1026 return NULL;
1027 }
1028 }
1029
1030
1031 #if OLD_LIBSYSTEM_SUPPORT
1032 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1033 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options)
1034 {
1035 if ( dyld::gLogAPIs )
1036 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr, moduleName, options); // note name/args translation
1037 ImageLoader* image = NULL;
1038 dyld::clearErrorMessage();
1039 try {
1040 const char* imageName = moduleName;
1041 image = dyld::loadFromMemory((const uint8_t*)object_addr, object_size, imageName);
1042
1043 if ( image != NULL ) {
1044 // support private bundles
1045 if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
1046 image->setHideExports();
1047
1048 // set up linking options
1049 bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
1050
1051 // load libraries, rebase, bind, to make this image usable
1052 dyld::link(image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL), UINT32_MAX);
1053
1054 // run initializers unless magic flag says not to
1055 if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
1056 dyld::runInitializers(image);
1057 }
1058 }
1059 catch (const char* msg) {
1060 if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
1061 dyldAPIhalt("NSLinkModule", msg);
1062 // not halting, so set error state for NSLinkEditError to find
1063 setLastError(NSLinkEditOtherError, 0, moduleName, msg);
1064 // if image was created for this bundle, destroy it
1065 if ( image != NULL ) {
1066 dyld::removeImage(image);
1067 ImageLoader::deleteImage(image);
1068 }
1069 image = NULL;
1070 free((void*)msg);
1071 }
1072 return ImageLoaderToNSModule(image);
1073 }
1074 #endif
1075
1076 NSSymbol NSLookupSymbolInModule(NSModule module, const char* symbolName)
1077 {
1078 if ( dyld::gLogAPIs )
1079 dyld::log("%s(%p, \"%s\")\n", __func__, (void *)module, symbolName);
1080 ImageLoader* image = NSModuleToImageLoader(module);
1081 if ( image == NULL )
1082 return NULL;
1083 return SymbolToNSSymbol(image->findExportedSymbol(symbolName, false, NULL));
1084 }
1085
1086 const char* NSNameOfModule(NSModule module)
1087 {
1088 if ( dyld::gLogAPIs )
1089 dyld::log("%s(%p)\n", __func__, module);
1090 ImageLoader* image = NSModuleToImageLoader(module);
1091 if ( image == NULL )
1092 return NULL;
1093 return image->getPath();
1094 }
1095
1096 const char* NSLibraryNameForModule(NSModule module)
1097 {
1098 if ( dyld::gLogAPIs )
1099 dyld::log("%s(%p)\n", __func__, module);
1100 ImageLoader* image = NSModuleToImageLoader(module);
1101 if ( image == NULL )
1102 return NULL;
1103 return image->getPath();
1104 }
1105
1106 bool NSUnLinkModule(NSModule module, uint32_t options)
1107 {
1108 if ( dyld::gLogAPIs )
1109 dyld::log("%s(%p, 0x%08X)\n", __func__, module, options);
1110 if ( module == NULL )
1111 return false;
1112 ImageLoader* image = NSModuleToImageLoader(module);
1113 if ( image == NULL )
1114 return false;
1115 dyld::runImageStaticTerminators(image);
1116 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 13) ) {
1117 __cxa_range_t ranges[image->segmentCount()];
1118 int rangeCount = 0;
1119 for (unsigned int j=0; j < image->segmentCount(); ++j) {
1120 if ( !image->segExecutable(j) )
1121 continue;
1122 ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
1123 ranges[rangeCount].length = image->segSize(j);
1124 ++rangeCount;
1125 }
1126 (*dyld::gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
1127 }
1128 dyld::removeImage(image);
1129
1130 if ( (options & NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED) != 0 )
1131 image->setLeaveMapped();
1132
1133 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1134
1135 // Only delete image if there is no ofi referencing it
1136 // That means the ofi was destroyed after linking, so no one is left to delete this image
1137 const size_t ofiCount = sObjectFileImages.size();
1138 bool found = false;
1139 for (size_t i=0; i < ofiCount; ++i) {
1140 NSObjectFileImage ofi = sObjectFileImages[i];
1141 if ( ofi->image == image )
1142 found = true;
1143 }
1144 if ( !found )
1145 ImageLoader::deleteImage(image);
1146
1147 return true;
1148 }
1149
1150 // internal name and parameters do not match public name and parameters...
1151 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit)
1152 {
1153 if ( dyld::gLogAPIs )
1154 dyld::log("NSLinkEditErrorHandlers()\n");
1155
1156 dyld::registerUndefinedHandler((dyld::UndefinedHandler)undefined);
1157 // no support for multiple or linkedit handlers
1158 }
1159
1160
1161
1162
1163 void NSLinkEditError(NSLinkEditErrors* c, int* errorNumber, const char** fileName, const char** errorString)
1164 {
1165 // FIXME FIXME
1166 *c = sLastErrorFileCode;
1167 *errorNumber = sLastErrorNo;
1168 *fileName = sLastErrorFilePath;
1169 *errorString = dyld::getErrorMessage();
1170 }
1171
1172
1173
1174 static void _dyld_register_binding_handler(void * (*bindingHandler)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions)
1175 {
1176 if ( dyld::gLogAPIs )
1177 dyld::log("%s()\n", __func__);
1178 dyld::gLinkContext.bindingHandler = bindingHandler;
1179 dyld::gLinkContext.bindingOptions = bindingOptions;
1180 }
1181
1182 #endif //DEPRECATED_APIS_SUPPORTED
1183
1184
1185 // Call by fork() in libSystem after the kernel trap is done on the child side
1186 void _dyld_fork_child()
1187 {
1188 if ( dyld::gLogAPIs )
1189 dyld::log("%s()\n", __func__);
1190 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1191 // in libSystem for the child of a fork. But dyld is built with a static copy
1192 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1193 //
1194 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1195 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1196 //
1197 extern mach_port_t mach_task_self_;
1198 mach_task_self_ = task_self_trap();
1199
1200 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1201 // page is not copied on fork. <rdar://problem/6797342>
1202 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1203 dyld::gProcessInfo->coreSymbolicationShmPage = NULL;
1204 // for safety, make sure child starts with clean systemOrderFlag
1205 dyld::gProcessInfo->systemOrderFlag = 0;
1206 }
1207
1208
1209 #if DEPRECATED_APIS_SUPPORTED
1210 // returns true if prebinding was used in main executable
1211 bool _dyld_launched_prebound()
1212 {
1213 if ( dyld::gLogAPIs )
1214 dyld::log("%s()\n", __func__);
1215
1216 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1217 return dyld::mainExecutablePrebound();
1218 }
1219
1220
1221 //
1222 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1223 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1224 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1225 // flag on the image for this module. If the module was found and it was
1226 // private then everything worked and TRUE is returned else FALSE is returned.
1227 //
1228 static bool NSMakePrivateModulePublic(NSModule module)
1229 {
1230 ImageLoader* image = NSModuleToImageLoader(module);
1231 if ( image != NULL ) {
1232 if ( image->hasHiddenExports() ) {
1233 image->setHideExports(false);
1234 return true;
1235 }
1236 }
1237 return false;
1238 }
1239
1240 #endif // DEPRECATED_APIS_SUPPORTED
1241
1242 int _dyld_func_lookup(const char* name, void** address)
1243 {
1244 for (const dyld_func* p = dyld_funcs; p->name != NULL; ++p) {
1245 if ( strcmp(p->name, name) == 0 ) {
1246 if( p->implementation == unimplemented )
1247 dyld::log("unimplemented dyld function: %s\n", p->name);
1248 *address = p->implementation;
1249 return true;
1250 }
1251 }
1252 *address = 0;
1253 return false;
1254 }
1255
1256
1257 static void registerThreadHelpers(const dyld::LibSystemHelpers* helpers)
1258 {
1259 dyld::gLibSystemHelpers = helpers;
1260
1261 #if !SUPPORT_ZERO_COST_EXCEPTIONS
1262 if ( helpers->version >= 5 ) {
1263 // create key use by dyld exception handling
1264 pthread_key_t key;
1265 int result = helpers->pthread_key_create(&key, NULL);
1266 if ( result == 0 )
1267 __Unwind_SjLj_SetThreadKey(key);
1268 }
1269 #endif
1270 }
1271
1272
1273 static void dlerrorClear()
1274 {
1275 if ( dyld::gLibSystemHelpers != NULL ) {
1276 // <rdar://problem/10595338> dlerror buffer leak
1277 // dlerrorClear() should not force allocation, but zero it if already allocated
1278 if ( dyld::gLibSystemHelpers->version >= 10 ) {
1279 if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
1280 return;
1281 }
1282
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 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
1309
1310 const bool leafName = (strchr(path, '/') == NULL);
1311 const bool absolutePath = (path[0] == '/');
1312 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1313 char canonicalPath[PATH_MAX];
1314 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1315 if ( !leafName ) {
1316 // make path canonical if it contains a // or ./
1317 if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
1318 const char* lastSlash = strrchr(path, '/');
1319 char dirPath[PATH_MAX];
1320 if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
1321 dirPath[lastSlash-path] = '\0';
1322 if ( realpath(dirPath, canonicalPath) ) {
1323 strlcat(canonicalPath, "/", sizeof(canonicalPath));
1324 if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
1325 // if all fit in buffer, use new canonical path
1326 path = canonicalPath;
1327 }
1328 }
1329 }
1330 }
1331 }
1332 #endif
1333 #if SUPPORT_ACCELERATE_TABLES
1334 if ( dyld::isPathInCache(path) )
1335 return true;
1336 #endif
1337
1338 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1339 // if requested path is to something in the dyld shared cache, always succeed
1340 if ( dyld::inSharedCache(path) )
1341 return true;
1342
1343 bool result = false;
1344 std::vector<const char*> rpathsFromCallerImage;
1345 try {
1346 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1347 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1348 // for dlopen, use rpath from caller image and from main executable
1349 if ( callerImage != NULL )
1350 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1351 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
1352 if ( callerImage != dyld::mainExecutable() ) {
1353 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1354 }
1355
1356 ImageLoader* image = NULL;
1357 dyld::LoadContext context;
1358 context.useSearchPaths = true;
1359 context.useFallbackPaths= leafName; // a partial path implies don't use fallback paths
1360 context.useLdLibraryPath= leafName; // a leafname implies should search
1361 context.implicitRPath = !absolutePath; // a non-absolute path implies try rpath searching
1362 context.matchByInstallName = true;
1363 context.dontLoad = false;
1364 context.mustBeBundle = false;
1365 context.mustBeDylib = false;
1366 context.canBePIE = true;
1367 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
1368 context.rpath = &callersRPaths; // rpaths from caller and main executable
1369
1370 unsigned cacheIndex;
1371 image = load(path, context, cacheIndex);
1372 if ( image != NULL ) {
1373 dyld::preflight(image, callersRPaths, cacheIndex); // image object deleted by dyld::preflight()
1374 result = true;
1375 }
1376 }
1377 catch (const char* msg) {
1378 const char* str = dyld::mkstringf("dlopen_preflight(%s): %s", path, msg);
1379 dlerrorSet(str);
1380 free((void*)str);
1381 free((void*)msg); // our free() will do nothing if msg is a string literal
1382 }
1383 // free rpaths (getRPaths() malloc'ed each string)
1384 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
1385 const char* str = *it;
1386 free((void*)str);
1387 }
1388 CRSetCrashLogMessage(NULL);
1389 return result;
1390 }
1391
1392 #if SUPPORT_ACCELERATE_TABLES
1393 bool static callerIsNonOSApp(void* callerAddress, const char** shortName)
1394 {
1395 *shortName = NULL;
1396 const mach_header* unusedMh;
1397 const char* unusedPath;
1398 unsigned unusedIndex;
1399 // any address in shared cache is not from app
1400 if ( dyld::addressInCache(callerAddress, &unusedMh, &unusedPath, &unusedIndex) )
1401 return false;
1402
1403 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1404 if ( callerImage == NULL )
1405 return false;
1406
1407 *shortName = callerImage->getShortName();
1408 return ( strncmp(callerImage->getPath(), "/var/containers/", 16) == 0 );
1409 }
1410 #endif
1411
1412 void* dlopen(const char* path, int mode)
1413 {
1414 if ( dyld::gLogAPIs )
1415 dyld::log("%s(%s, 0x%08X)\n", __func__, ((path==NULL) ? "NULL" : path), mode);
1416
1417 #if SUPPORT_ACCELERATE_TABLES
1418 if ( dyld::gLogAppAPIs ) {
1419 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1420 const char* shortName;
1421 if ( callerIsNonOSApp(callerAddress, &shortName) ) {
1422 dyld::log("%s: %s(%s, 0x%08X)\n", shortName, __func__, ((path==NULL) ? "NULL" : path), mode);
1423 }
1424 }
1425 #endif
1426
1427 dlerrorClear();
1428
1429 // passing NULL for path means return magic object
1430 if ( path == NULL ) {
1431 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1432 if ( (mode & RTLD_FIRST) != 0 )
1433 return RTLD_MAIN_ONLY;
1434 else
1435 return RTLD_DEFAULT;
1436 }
1437
1438 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1439 bool lockHeld = false;
1440 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 4) ) {
1441 dyld::gLibSystemHelpers->acquireGlobalDyldLock();
1442 CRSetCrashLogMessage("dyld: in dlopen()");
1443 lockHeld = true;
1444 }
1445
1446 void* result = NULL;
1447 const bool leafName = (strchr(path, '/') == NULL);
1448 const bool absolutePath = (path[0] == '/');
1449 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1450 char canonicalPath[PATH_MAX];
1451 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1452 if ( !leafName ) {
1453 // make path canonical if it contains a // or ./
1454 if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
1455 const char* lastSlash = strrchr(path, '/');
1456 char dirPath[PATH_MAX];
1457 if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
1458 dirPath[lastSlash-path] = '\0';
1459 if ( realpath(dirPath, canonicalPath) ) {
1460 strlcat(canonicalPath, "/", sizeof(canonicalPath));
1461 if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
1462 // if all fit in buffer, use new canonical path
1463 path = canonicalPath;
1464 }
1465 }
1466 }
1467 }
1468 }
1469 #endif
1470 #if SUPPORT_ACCELERATE_TABLES
1471 if ( dyld::dlopenFromCache(path, mode, &result) ) {
1472 // Note: dlopenFromCache() releases the lock
1473 if ( dyld::gLogAPIs )
1474 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1475 return result;
1476 }
1477 #endif
1478
1479 ImageLoader* image = NULL;
1480 std::vector<const char*> rpathsFromCallerImage;
1481 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
1482 try {
1483 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1484 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1485 if ( (mode & RTLD_NOLOAD) == 0 ) {
1486 // for dlopen, use rpath from caller image and from main executable
1487 if ( callerImage != NULL )
1488 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1489 if ( callerImage != dyld::mainExecutable() )
1490 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1491 }
1492
1493 dyld::LoadContext context;
1494 context.useSearchPaths = true;
1495 context.useFallbackPaths= leafName; // a partial path means no fallback paths
1496 context.useLdLibraryPath= leafName; // a leafname implies should search
1497 context.implicitRPath = !absolutePath; // a non-absolute path implies try rpath searching
1498 context.matchByInstallName = true;
1499 context.dontLoad = ( (mode & RTLD_NOLOAD) != 0 );
1500 context.mustBeBundle = false;
1501 context.mustBeDylib = false;
1502 context.canBePIE = true;
1503 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
1504 context.rpath = &callersRPaths; // rpaths from caller and main executable
1505
1506 unsigned cacheIndex;
1507 image = load(path, context, cacheIndex);
1508 #if SUPPORT_ACCELERATE_TABLES
1509 if ( (image != NULL) && (cacheIndex != UINT32_MAX) ) {
1510 // found in cache, but under a different path
1511 const char* betterPath = dyld::getPathFromIndex(cacheIndex);
1512 if ( (betterPath != NULL) && dyld::dlopenFromCache(betterPath, mode, &result) ) {
1513 // Note: dlopenFromCache() releases the lock
1514 if ( dyld::gLogAPIs )
1515 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1516 return result;
1517 }
1518 }
1519 #endif
1520 if ( image != NULL ) {
1521 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1522 // this image is not garbage collected
1523 image->incrementDlopenReferenceCount();
1524 // link in all dependents
1525 if ( (mode & RTLD_NOLOAD) == 0 ) {
1526 bool alreadyLinked = image->isLinked();
1527 bool forceLazysBound = ( (mode & RTLD_NOW) != 0 );
1528 dyld::link(image, forceLazysBound, false, callersRPaths, cacheIndex);
1529 if ( ! alreadyLinked ) {
1530 // only hide exports if image is not already in use
1531 if ( (mode & RTLD_LOCAL) != 0 )
1532 image->setHideExports(true);
1533 }
1534 }
1535
1536 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1537 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1538 // The subtle differences are:
1539 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1540 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1541 if ( (mode & RTLD_NODELETE) != 0 )
1542 image->setLeaveMapped();
1543
1544 // release global dyld lock early, this enables initializers to do threaded operations
1545 if ( lockHeld ) {
1546 CRSetCrashLogMessage(NULL);
1547 dyld::gLibSystemHelpers->releaseGlobalDyldLock();
1548 lockHeld = false;
1549 }
1550
1551 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1552 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1553 // called from within an initializer because it can cause initializers to run
1554 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1555 // to run, then don't use RTLD_NOLOAD.
1556 if ( (mode & RTLD_NOLOAD) == 0 ) {
1557 // run initializers
1558 dyld::runInitializers(image);
1559 }
1560
1561 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1562 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1563 if ( (mode & RTLD_FIRST) != 0 )
1564 result = (void*)(((uintptr_t)image)|1);
1565 else
1566 result = image;
1567 }
1568 }
1569 catch (const char* msg) {
1570 if ( image != NULL ) {
1571 // load() succeeded but, link() failed
1572 // back down reference count and do GC
1573 image->decrementDlopenReferenceCount();
1574 if ( image->dlopenCount() == 0 )
1575 dyld::garbageCollectImages();
1576 }
1577 const char* str = dyld::mkstringf("dlopen(%s, %d): %s", path, mode, msg);
1578 if ( dyld::gLogAPIs )
1579 dyld::log(" %s() failed, error: '%s'\n", __func__, str);
1580 dlerrorSet(str);
1581 free((void*)str);
1582 free((void*)msg); // our free() will do nothing if msg is a string literal
1583 result = NULL;
1584 }
1585 // free rpaths (getRPaths() malloc'ed each string)
1586 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
1587 const char* str = *it;
1588 free((void*)str);
1589 }
1590
1591 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1592 if ( (mode & RTLD_NOLOAD) && (result == NULL) ) {
1593 dlerrorSet("image not already loaded");
1594 }
1595
1596 if ( lockHeld ) {
1597 CRSetCrashLogMessage(NULL);
1598 dyld::gLibSystemHelpers->releaseGlobalDyldLock();
1599 }
1600 if ( dyld::gLogAPIs && (result != NULL) )
1601 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1602 return result;
1603 }
1604
1605
1606
1607 int dlclose(void* handle)
1608 {
1609 if ( dyld::gLogAPIs )
1610 dyld::log("%s(%p)\n", __func__, handle);
1611
1612 // silently accept magic handles for main executable
1613 if ( handle == RTLD_MAIN_ONLY )
1614 return 0;
1615 if ( handle == RTLD_DEFAULT )
1616 return 0;
1617
1618 ImageLoader* image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
1619 if ( dyld::validImage(image) ) {
1620 dlerrorClear();
1621 // decrement use count
1622 if ( image->decrementDlopenReferenceCount() ) {
1623 dlerrorSet("dlclose() called too many times");
1624 return -1;
1625 }
1626 // remove image if reference count went to zero
1627 if ( image->dlopenCount() == 0 )
1628 dyld::garbageCollectImages();
1629 return 0;
1630 }
1631 else {
1632 dlerrorSet("invalid handle passed to dlclose()");
1633 return -1;
1634 }
1635 }
1636
1637
1638
1639 int dladdr(const void* address, Dl_info* info)
1640 {
1641 if ( dyld::gLogAPIs )
1642 dyld::log("%s(%p, %p)\n", __func__, address, info);
1643
1644 CRSetCrashLogMessage("dyld: in dladdr()");
1645 #if SUPPORT_ACCELERATE_TABLES
1646 if ( dyld::dladdrFromCache(address, info) ) {
1647 CRSetCrashLogMessage(NULL);
1648 return 1; // success
1649 }
1650 #endif
1651
1652 ImageLoader* image = dyld::findImageContainingAddress(address);
1653 if ( image != NULL ) {
1654 info->dli_fname = image->getRealPath();
1655 info->dli_fbase = (void*)image->machHeader();
1656 if ( address == info->dli_fbase ) {
1657 // special case lookup of header
1658 info->dli_sname = "__dso_handle";
1659 info->dli_saddr = info->dli_fbase;
1660 CRSetCrashLogMessage(NULL);
1661 return 1; // success
1662 }
1663 // find closest symbol in the image
1664 info->dli_sname = image->findClosestSymbol(address, (const void**)&info->dli_saddr);
1665 // never return the mach_header symbol
1666 if ( info->dli_saddr == info->dli_fbase ) {
1667 info->dli_sname = NULL;
1668 info->dli_saddr = NULL;
1669 CRSetCrashLogMessage(NULL);
1670 return 1; // success
1671 }
1672 if ( info->dli_sname != NULL ) {
1673 if ( info->dli_sname[0] == '_' )
1674 info->dli_sname = info->dli_sname +1; // strip off leading underscore
1675 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1676 CRSetCrashLogMessage(NULL);
1677 return 1; // success
1678 }
1679 info->dli_sname = NULL;
1680 info->dli_saddr = NULL;
1681 CRSetCrashLogMessage(NULL);
1682 return 1; // success
1683 }
1684 CRSetCrashLogMessage(NULL);
1685 return 0; // failure
1686 }
1687
1688
1689 char* dlerror()
1690 {
1691 if ( dyld::gLogAPIs )
1692 dyld::log("%s()\n", __func__);
1693
1694 if ( dyld::gLibSystemHelpers != NULL ) {
1695 // if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
1696 if ( dyld::gLibSystemHelpers->version >= 10 ) {
1697 if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
1698 return NULL;
1699 }
1700
1701 // first char of buffer is flag whether string (starting at second char) is valid
1702 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
1703 if ( buffer[0] != '\0' ) { // if valid buffer
1704 buffer[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1705 return &buffer[1]; // return message
1706 }
1707 }
1708 return NULL;
1709 }
1710
1711 void* dlsym(void* handle, const char* symbolName)
1712 {
1713 if ( dyld::gLogAPIs )
1714 dyld::log("%s(%p, %s)\n", __func__, handle, symbolName);
1715
1716 #if SUPPORT_ACCELERATE_TABLES
1717 if ( dyld::gLogAppAPIs ) {
1718 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1719 const char* shortName;
1720 if ( callerIsNonOSApp(callerAddress, &shortName) ) {
1721 dyld::log("%s: %s(%p, %s)\n", shortName, __func__, handle, symbolName);
1722 }
1723 }
1724 #endif
1725
1726 CRSetCrashLogMessage("dyld: in dlsym()");
1727 dlerrorClear();
1728
1729 const ImageLoader* image;
1730 const ImageLoader::Symbol* sym;
1731 void* result;
1732
1733 // dlsym() assumes symbolName passed in is same as in C source code
1734 // dyld assumes all symbol names have an underscore prefix
1735 char underscoredName[strlen(symbolName)+2];
1736 underscoredName[0] = '_';
1737 strcpy(&underscoredName[1], symbolName);
1738
1739 // magic "search all" handle
1740 if ( handle == RTLD_DEFAULT ) {
1741 if ( dyld::flatFindExportedSymbol(underscoredName, &sym, &image) ) {
1742 CRSetCrashLogMessage(NULL);
1743 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, NULL, false, underscoredName);
1744 if ( dyld::gLogAPIs )
1745 dyld::log(" %s(RTLD_DEFAULT, %s) ==> %p\n", __func__, symbolName, result);
1746 return result;
1747 }
1748 const char* str = dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName);
1749 dlerrorSet(str);
1750 free((void*)str);
1751 CRSetCrashLogMessage(NULL);
1752 if ( dyld::gLogAPIs )
1753 dyld::log(" %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__, symbolName);
1754 return NULL;
1755 }
1756
1757 // magic "search only main executable" handle
1758 else if ( handle == RTLD_MAIN_ONLY ) {
1759 image = dyld::mainExecutable();
1760 sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
1761 if ( sym != NULL ) {
1762 CRSetCrashLogMessage(NULL);
1763 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, NULL, false, underscoredName);
1764 if ( dyld::gLogAPIs )
1765 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__, symbolName, result);
1766 return result;
1767 }
1768 const char* str = dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName);
1769 dlerrorSet(str);
1770 free((void*)str);
1771 CRSetCrashLogMessage(NULL);
1772 if ( dyld::gLogAPIs )
1773 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__, symbolName);
1774 return NULL;
1775 }
1776
1777 // magic "search what I would see" handle
1778 else if ( handle == RTLD_NEXT ) {
1779 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1780 #if SUPPORT_ACCELERATE_TABLES
1781 const mach_header* mh;
1782 const char* path;
1783 unsigned index;
1784 if ( dyld::addressInCache(callerAddress, &mh, &path, &index) ) {
1785 // if dylib in cache is calling dlsym(RTLD_NEXT,xxx) handle search differently
1786 result = dyld::dlsymFromCache(RTLD_NEXT, underscoredName, index);
1787 if ( dyld::gLogAPIs )
1788 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__, symbolName, result);
1789 return result;
1790 }
1791 #endif
1792 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1793 sym = callerImage->findExportedSymbolInDependentImages(underscoredName, dyld::gLinkContext, &image); // don't search image, but do search what it links against
1794 if ( sym != NULL ) {
1795 CRSetCrashLogMessage(NULL);
1796 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext , callerImage, false, underscoredName);
1797 if ( dyld::gLogAPIs )
1798 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__, symbolName, result);
1799 return result;
1800 }
1801 const char* str = dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName);
1802 dlerrorSet(str);
1803 free((void*)str);
1804 CRSetCrashLogMessage(NULL);
1805 if ( dyld::gLogAPIs )
1806 dyld::log(" %s(RTLD_NEXT, %s) ==> NULL\n", __func__, symbolName);
1807 return NULL;
1808 }
1809 // magic "search me, then what I would see" handle
1810 else if ( handle == RTLD_SELF ) {
1811 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1812 #if SUPPORT_ACCELERATE_TABLES
1813 const mach_header* mh;
1814 const char* path;
1815 unsigned index;
1816 if ( dyld::addressInCache(callerAddress, &mh, &path, &index) ) {
1817 // if dylib in cache is calling dlsym(RTLD_SELF,xxx) handle search differently
1818 result = dyld::dlsymFromCache(RTLD_SELF, underscoredName, index);
1819 if ( dyld::gLogAPIs )
1820 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__, symbolName, result);
1821 return result;
1822 }
1823 #endif
1824 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1825 sym = callerImage->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
1826 if ( sym != NULL ) {
1827 CRSetCrashLogMessage(NULL);
1828 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage, false, underscoredName);
1829 if ( dyld::gLogAPIs )
1830 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__, symbolName, result);
1831 return result;
1832 }
1833 const char* str = dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName);
1834 dlerrorSet(str);
1835 free((void*)str);
1836 CRSetCrashLogMessage(NULL);
1837 if ( dyld::gLogAPIs )
1838 dyld::log(" %s(RTLD_SELF, %s) ==> NULL\n", __func__, symbolName);
1839 return NULL;
1840 }
1841 #if SUPPORT_ACCELERATE_TABLES
1842 // check for mega dylib handle
1843 else if ( dyld::isCacheHandle(handle) ) {
1844 result = dyld::dlsymFromCache(handle, underscoredName, 0);
1845 if ( dyld::gLogAPIs )
1846 dyld::log(" %s(%p, %s) ==> %p\n", __func__, handle, symbolName, result);
1847 return result;
1848 }
1849 #endif
1850 // real handle
1851 image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
1852 if ( dyld::validImage(image) ) {
1853 if ( (((uintptr_t)handle) & 1) != 0 )
1854 sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
1855 else
1856 sym = image->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
1857
1858 if ( sym != NULL ) {
1859 CRSetCrashLogMessage(NULL);
1860 ImageLoader* callerImage = NULL;
1861 if ( sDynamicInterposing ) {
1862 // only take time to look up caller, if dynamic interposing in use
1863 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1864 callerImage = dyld::findImageContainingAddress(callerAddress);
1865 }
1866 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage, false, underscoredName);
1867 if ( dyld::gLogAPIs )
1868 dyld::log(" %s(%p, %s) ==> %p\n", __func__, handle, symbolName, result);
1869 return result;
1870 }
1871 const char* str = dyld::mkstringf("dlsym(%p, %s): symbol not found", handle, symbolName);
1872 dlerrorSet(str);
1873 free((void*)str);
1874 }
1875 else {
1876 dlerrorSet("invalid handle passed to dlsym()");
1877 }
1878 CRSetCrashLogMessage(NULL);
1879 if ( dyld::gLogAPIs )
1880 dyld::log(" %s(%p, %s) ==> NULL\n", __func__, handle, symbolName);
1881 return NULL;
1882 }
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893 const struct dyld_all_image_infos* _dyld_get_all_image_infos()
1894 {
1895 return dyld::gProcessInfo;
1896 }
1897
1898
1899 #if SUPPORT_ZERO_COST_EXCEPTIONS
1900 static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info)
1901 {
1902 //if ( dyld::gLogAPIs )
1903 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
1904
1905 #if SUPPORT_ACCELERATE_TABLES
1906 if ( dyld::findUnwindSections(addr, info) )
1907 return true;
1908 #endif
1909 ImageLoader* image = dyld::findImageContainingAddress(addr);
1910 if ( image != NULL ) {
1911 image->getUnwindInfo(info);
1912 return true;
1913 }
1914 return false;
1915 }
1916 #endif
1917
1918
1919 const char* dyld_image_path_containing_address(const void* address)
1920 {
1921 if ( dyld::gLogAPIs )
1922 dyld::log("%s(%p)\n", __func__, address);
1923
1924 #if SUPPORT_ACCELERATE_TABLES
1925 const mach_header* mh;
1926 const char* path;
1927 if ( dyld::addressInCache(address, &mh, &path) )
1928 return path;
1929 #endif
1930
1931 ImageLoader* image = dyld::findImageContainingAddress(address);
1932 if ( image != NULL )
1933 return image->getRealPath();
1934 return NULL;
1935 }
1936
1937
1938
1939 bool dyld_shared_cache_some_image_overridden()
1940 {
1941 return dyld::gSharedCacheOverridden;
1942 }
1943
1944
1945 void dyld_dynamic_interpose(const struct mach_header* mh, const struct dyld_interpose_tuple array[], size_t count)
1946 {
1947 if ( mh == NULL )
1948 return;
1949 if ( array == NULL )
1950 return;
1951 if ( count == 0 )
1952 return;
1953 ImageLoader* image = dyld::findImageByMachHeader(mh);
1954 if ( image == NULL )
1955 return;
1956
1957 // make pass at bound references in this image and update them
1958 dyld::gLinkContext.dynamicInterposeArray = array;
1959 dyld::gLinkContext.dynamicInterposeCount = count;
1960 image->dynamicInterpose(dyld::gLinkContext);
1961 dyld::gLinkContext.dynamicInterposeArray = NULL;
1962 dyld::gLinkContext.dynamicInterposeCount = 0;
1963
1964 // leave interposing info so any future (lazy) binding will get it too
1965 image->addDynamicInterposingTuples(array, count);
1966
1967 sDynamicInterposing = true;
1968 }
1969
1970
1971 bool _dyld_is_memory_immutable(const void* addr, size_t length)
1972 {
1973 if ( dyld::gLogAPIs )
1974 dyld::log("%s(%p, %ld)\n", __func__, addr, length);
1975
1976 uintptr_t checkStart = (uintptr_t)addr;
1977 uintptr_t checkEnd = checkStart + length;
1978
1979 // quick check to see if in r/o region of shared cache. If so return true.
1980 const DyldSharedCache* cache = (DyldSharedCache*)dyld::imMemorySharedCacheHeader();
1981 if ( cache != nullptr ) {
1982 const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)((char*)cache + cache->header.mappingOffset);
1983 uintptr_t roStart = (uintptr_t)cache;
1984 uintptr_t roEnd = roStart + (uintptr_t)mappings[0].size;
1985 if ( (roStart < checkStart) && (checkEnd < roEnd) )
1986 return true;
1987 }
1988
1989 // Otherwise find if addr is in a dyld loaded image
1990 ImageLoader* image = dyld::findImageContainingAddress(addr);
1991 if ( image != NULL ) {
1992 // <rdar://problem/24091154> already checked for r/o portion of cache
1993 if ( image->inSharedCache() )
1994 return false;
1995 if ( !image->neverUnload() )
1996 return false;
1997 for (unsigned i=0, e=image->segmentCount(); i < e; ++i) {
1998 if ( (image->segActualLoadAddress(i) < checkStart) && (checkEnd < image->segActualEndAddress(i)) ) {
1999 return !image->segWriteable(i);
2000 }
2001 }
2002 }
2003 return false;
2004 }
2005
2006
2007
2008 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped,
2009 _dyld_objc_notify_init init,
2010 _dyld_objc_notify_unmapped unmapped)
2011 {
2012 dyld::registerObjCNotifiers(mapped, init, unmapped);
2013 }
2014
2015
2016 bool _dyld_get_shared_cache_uuid(uuid_t uuid)
2017 {
2018 return dyld::sharedCacheUUID(uuid);
2019 }
2020
2021 const void* _dyld_get_shared_cache_range(size_t* length)
2022 {
2023 const DyldSharedCache* cache = (DyldSharedCache*)dyld::imMemorySharedCacheHeader();
2024 if ( cache != nullptr ) {
2025 const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)((char*)cache + cache->header.mappingOffset);
2026 *length = (size_t)((mappings[2].address + mappings[2].size) - mappings[0].address);
2027 return cache;
2028 }
2029 return nullptr;
2030 }
2031
2032
2033