dyld-551.3.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 const char* symbolToFind = symbolName;
649 try {
650 if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY ) {
651 image->bindAllLazyPointers(dyld::gLinkContext, true);
652 }
653 else if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW ) {
654 image->bindAllLazyPointers(dyld::gLinkContext, false);
655 }
656 }
657 catch (const char* msg) {
658 if ( (options & NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR) == 0 ) {
659 dyldAPIhalt(__func__, msg);
660 }
661 }
662 symbol = image->findExportedSymbol(symbolToFind, true, NULL);
663 }
664 if ( dyld::gLogAPIs && (symbol == NULL) )
665 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__, mh, symbolName, options);
666 return SymbolToNSSymbol(symbol);
667 }
668
669
670 // Note: This cannot have public name because dyld is built with a static copy of libc.a
671 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
672 static bool client_NSIsSymbolNameDefined(const char* symbolName)
673 {
674 if ( dyld::gLogAPIs )
675 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName);
676 const ImageLoader* image;
677 const ImageLoader::Symbol* sym;
678 return dyld::flatFindExportedSymbol(symbolName, &sym, &image);
679 }
680
681 bool NSIsSymbolNameDefinedWithHint(const char* symbolName, const char* libraryNameHint)
682 {
683 if ( dyld::gLogAPIs )
684 dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
685 const ImageLoader* image;
686 const ImageLoader::Symbol* sym;
687 bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
688 if ( ! found ) {
689 // hint failed, do slow search of all images
690 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
691 }
692 if ( !found && dyld::gLogAPIs )
693 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__, symbolName, libraryNameHint);
694 return found;
695 }
696
697 const char* NSNameOfSymbol(NSSymbol symbol)
698 {
699 if ( dyld::gLogAPIs )
700 dyld::log("%s(%p)\n", __func__, (void *)symbol);
701 const char* result = NULL;
702 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
703 if ( image != NULL )
704 result = image->getExportedSymbolName(NSSymbolToSymbol(symbol));
705 return result;
706 }
707
708 void* NSAddressOfSymbol(NSSymbol symbol)
709 {
710 if ( dyld::gLogAPIs )
711 dyld::log("%s(%p)\n", __func__, (void *)symbol);
712 if ( symbol == NULL )
713 return NULL;
714 void* result = NULL;
715 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
716 if ( image != NULL )
717 result = (void*)image->getExportedSymbolAddress(NSSymbolToSymbol(symbol), dyld::gLinkContext);
718 return result;
719 }
720
721 NSModule NSModuleForSymbol(NSSymbol symbol)
722 {
723 if ( dyld::gLogAPIs )
724 dyld::log("%s(%p)\n", __func__, (void *)symbol);
725 NSModule result = NULL;
726 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
727 if ( image != NULL )
728 result = ImageLoaderToNSModule(image);
729 return result;
730 }
731
732
733
734
735 bool _dyld_all_twolevel_modules_prebound(void)
736 {
737 if ( dyld::gLogAPIs )
738 dyld::log("%s()\n", __func__);
739 return FALSE;
740 }
741
742 bool _dyld_bind_fully_image_containing_address(const void* address)
743 {
744 if ( dyld::gLogAPIs )
745 dyld::log("%s(%p)\n", __func__, address);
746 dyld::clearErrorMessage();
747 ImageLoader* image = dyld::findImageContainingAddress(address);
748 if ( image != NULL ) {
749 try {
750 image->bindAllLazyPointers(dyld::gLinkContext, true);
751 return true;
752 }
753 catch (const char* msg) {
754 dyldAPIhalt(__func__, msg);
755 }
756 }
757 return false;
758 }
759
760 bool _dyld_image_containing_address(const void* address)
761 {
762 if ( dyld::gLogAPIs )
763 dyld::log("%s(%p)\n", __func__, address);
764 ImageLoader *imageLoader = dyld::findImageContainingAddress(address);
765 return (NULL != imageLoader);
766 }
767
768 static NSObjectFileImage createObjectImageFile(ImageLoader* image, const void* address = NULL, size_t len=0)
769 {
770 NSObjectFileImage result = new __NSObjectFileImage();
771 result->image = image;
772 result->imageBaseAddress = address;
773 result->imageLength = len;
774 sObjectFileImages.push_back(result);
775 return result;
776 }
777
778 NSObjectFileImageReturnCode NSCreateObjectFileImageFromFile(const char* pathName, NSObjectFileImage *objectFileImage)
779 {
780 if ( dyld::gLogAPIs )
781 dyld::log("%s(\"%s\", ...)\n", __func__, pathName);
782 try {
783 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
784 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
785
786 dyld::LoadContext context;
787 context.useSearchPaths = false;
788 context.useFallbackPaths = false;
789 context.useLdLibraryPath = false;
790 context.implicitRPath = false;
791 context.matchByInstallName = false;
792 context.dontLoad = false;
793 context.mustBeBundle = true;
794 context.mustBeDylib = false;
795 context.canBePIE = false;
796 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
797 context.rpath = NULL; // support not yet implemented
798
799 unsigned cacheIndex;
800 ImageLoader* image = dyld::load(pathName, context, cacheIndex);
801 // Note: We DO NOT link the image! NSLinkModule will do that
802 if ( image != NULL ) {
803 if ( !image->isBundle() ) {
804 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
805 return NSObjectFileImageInappropriateFile;
806 }
807 *objectFileImage = createObjectImageFile(image);
808 return NSObjectFileImageSuccess;
809 }
810 }
811 catch (const char* msg) {
812 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
813 dyld::garbageCollectImages();
814 free((void*)msg);
815 return NSObjectFileImageInappropriateFile;
816 }
817 return NSObjectFileImageFailure;
818 }
819
820
821 NSObjectFileImageReturnCode NSCreateObjectFileImageFromMemory(const void* address, size_t size, NSObjectFileImage *objectFileImage)
822 {
823 if ( dyld::gLogAPIs )
824 dyld::log("%s(%p, %lu, %p)\n", __func__, address, size, objectFileImage);
825
826 try {
827 ImageLoader* image = dyld::loadFromMemory((const uint8_t*)address, size, NULL);
828 if ( ! image->isBundle() ) {
829 // this API can only be used with bundles...
830 dyld::garbageCollectImages();
831 return NSObjectFileImageInappropriateFile;
832 }
833 // Note: We DO NOT link the image! NSLinkModule will do that
834 if ( image != NULL ) {
835 *objectFileImage = createObjectImageFile(image, address, size);
836 return NSObjectFileImageSuccess;
837 }
838 }
839 catch (const char* msg) {
840 free((void*)msg);
841 dyld::garbageCollectImages();
842 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
843 }
844 return NSObjectFileImageFailure;
845 }
846
847 static bool validOFI(NSObjectFileImage objectFileImage)
848 {
849 const size_t ofiCount = sObjectFileImages.size();
850 for (size_t i=0; i < ofiCount; ++i) {
851 if ( sObjectFileImages[i] == objectFileImage )
852 return true;
853 }
854 return false;
855 }
856
857 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage)
858 {
859 if ( dyld::gLogAPIs )
860 dyld::log("%s(%p)\n", __func__, objectFileImage);
861
862 if ( validOFI(objectFileImage) ) {
863 // a failure during NSLinkModule will delete the image
864 if ( objectFileImage->image != NULL ) {
865 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
866 // and we should delete it
867 bool linkedImage = dyld::validImage(objectFileImage->image);
868 if ( ! linkedImage ) {
869 ImageLoader::deleteImage(objectFileImage->image);
870 objectFileImage->image = NULL;
871 }
872 }
873
874 // remove from list of ofi's
875 for (std::vector<NSObjectFileImage>::iterator it=sObjectFileImages.begin(); it != sObjectFileImages.end(); it++) {
876 if ( *it == objectFileImage ) {
877 sObjectFileImages.erase(it);
878 break;
879 }
880 }
881
882 // if object was created from a memory, release that memory
883 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
884 if ( objectFileImage->imageBaseAddress != NULL ) {
885 bool freed = false;
886 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 6) ) {
887 size_t sz = (*dyld::gLibSystemHelpers->malloc_size)(objectFileImage->imageBaseAddress);
888 if ( sz != 0 ) {
889 (*dyld::gLibSystemHelpers->free)((void*)(objectFileImage->imageBaseAddress));
890 freed = true;
891 }
892 }
893 if ( ! freed )
894 vm_deallocate(mach_task_self(), (vm_address_t)objectFileImage->imageBaseAddress, objectFileImage->imageLength);
895 }
896
897 // free ofi object
898 delete objectFileImage;
899
900 return true;
901 }
902 return false;
903 }
904
905 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage)
906 {
907 if ( dyld::gLogAPIs )
908 dyld::log("%s(%p)\n", __func__, objectFileImage);
909 return objectFileImage->image->getExportedSymbolCount();
910 }
911
912 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal)
913 {
914 if ( dyld::gLogAPIs )
915 dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
916 const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedExportedSymbol(ordinal);
917 return objectFileImage->image->getExportedSymbolName(sym);
918 }
919
920 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage)
921 {
922 if ( dyld::gLogAPIs )
923 dyld::log("%s(%p)\n", __func__, objectFileImage);
924 return objectFileImage->image->getImportedSymbolCount();
925 }
926
927 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal,
928 bool* tentative_definition)
929 {
930 if ( dyld::gLogAPIs )
931 dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
932 const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedImportedSymbol(ordinal);
933 if ( tentative_definition != NULL ) {
934 ImageLoader::ReferenceFlags flags = objectFileImage->image->getImportedSymbolInfo(sym);
935 if ( (flags & ImageLoader::kTentativeDefinition) != 0 )
936 *tentative_definition = true;
937 else
938 *tentative_definition = false;
939 }
940 return objectFileImage->image->getImportedSymbolName(sym);
941 }
942
943 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage,
944 const char* segmentName, const char* sectionName, unsigned long* size)
945 {
946 if ( dyld::gLogAPIs )
947 dyld::log("%s(%p,%s, %s)\n", __func__, objectFileImage, segmentName, sectionName);
948
949 void* start;
950 size_t length;
951 if ( objectFileImage->image->getSectionContent(segmentName, sectionName, &start, &length) ) {
952 if ( size != NULL )
953 *size = length;
954 return start;
955 }
956 return NULL;
957 }
958
959
960
961 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage, const char* symbolName)
962 {
963 if ( dyld::gLogAPIs )
964 dyld::log("%s(%p,%s)\n", __func__, objectFileImage, symbolName);
965 const ImageLoader::Symbol* sym = objectFileImage->image->findExportedSymbol(symbolName, true, NULL);
966 return ( sym != NULL );
967 }
968
969
970
971 NSModule NSLinkModule(NSObjectFileImage objectFileImage, const char* moduleName, uint32_t options)
972 {
973 if ( dyld::gLogAPIs )
974 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, objectFileImage, moduleName, options);
975
976 dyld::clearErrorMessage();
977 try {
978 if ( (options & NSLINKMODULE_OPTION_CAN_UNLOAD) != 0 )
979 objectFileImage->image->setCanUnload();
980
981 // NSLinkModule allows a bundle to be link multpile times
982 // each link causes the bundle to be copied to a new address
983 if ( objectFileImage->image->isLinked() ) {
984 // already linked, so clone a new one and link it
985 objectFileImage->image = dyld::cloneImage(objectFileImage->image);
986 }
987
988 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
989 if ( objectFileImage->image->getPath() == NULL ) {
990 objectFileImage->image->setPath(moduleName);
991 // <rdar://problem/8812589> dyld has NULL paths in image info array
992 dyld_image_info info;
993 info.imageLoadAddress = objectFileImage->image->machHeader();
994 info.imageFilePath = moduleName;
995 info.imageFileModDate = 0;
996 addImagesToAllImages(1, &info);
997 }
998
999 // support private bundles
1000 if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
1001 objectFileImage->image->setHideExports();
1002
1003 // set up linking options
1004 bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
1005
1006 // load libraries, rebase, bind, to make this image usable
1007 dyld::link(objectFileImage->image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL), UINT32_MAX);
1008
1009 // bump reference count to keep this bundle from being garbage collected
1010 objectFileImage->image->incrementDlopenReferenceCount();
1011
1012 // run initializers unless magic flag says not to
1013 if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
1014 dyld::runInitializers(objectFileImage->image);
1015
1016 return ImageLoaderToNSModule(objectFileImage->image);
1017 }
1018 catch (const char* msg) {
1019 dyld::garbageCollectImages();
1020 if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
1021 dyldAPIhalt(__func__, msg);
1022 // not halting, so set error state for NSLinkEditError to find
1023 setLastError(NSLinkEditOtherError, 0, moduleName, msg);
1024 // dyld::link() deleted the image so lose our reference
1025 objectFileImage->image = NULL;
1026 free((void*)msg);
1027 return NULL;
1028 }
1029 }
1030
1031
1032 #if OLD_LIBSYSTEM_SUPPORT
1033 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1034 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options)
1035 {
1036 if ( dyld::gLogAPIs )
1037 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr, moduleName, options); // note name/args translation
1038 ImageLoader* image = NULL;
1039 dyld::clearErrorMessage();
1040 try {
1041 const char* imageName = moduleName;
1042 image = dyld::loadFromMemory((const uint8_t*)object_addr, object_size, imageName);
1043
1044 if ( image != NULL ) {
1045 // support private bundles
1046 if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
1047 image->setHideExports();
1048
1049 // set up linking options
1050 bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
1051
1052 // load libraries, rebase, bind, to make this image usable
1053 dyld::link(image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL), UINT32_MAX);
1054
1055 // run initializers unless magic flag says not to
1056 if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
1057 dyld::runInitializers(image);
1058 }
1059 }
1060 catch (const char* msg) {
1061 if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
1062 dyldAPIhalt("NSLinkModule", msg);
1063 // not halting, so set error state for NSLinkEditError to find
1064 setLastError(NSLinkEditOtherError, 0, moduleName, msg);
1065 // if image was created for this bundle, destroy it
1066 if ( image != NULL ) {
1067 dyld::removeImage(image);
1068 ImageLoader::deleteImage(image);
1069 }
1070 image = NULL;
1071 free((void*)msg);
1072 }
1073 return ImageLoaderToNSModule(image);
1074 }
1075 #endif
1076
1077 NSSymbol NSLookupSymbolInModule(NSModule module, const char* symbolName)
1078 {
1079 if ( dyld::gLogAPIs )
1080 dyld::log("%s(%p, \"%s\")\n", __func__, (void *)module, symbolName);
1081 ImageLoader* image = NSModuleToImageLoader(module);
1082 if ( image == NULL )
1083 return NULL;
1084 return SymbolToNSSymbol(image->findExportedSymbol(symbolName, false, NULL));
1085 }
1086
1087 const char* NSNameOfModule(NSModule module)
1088 {
1089 if ( dyld::gLogAPIs )
1090 dyld::log("%s(%p)\n", __func__, module);
1091 ImageLoader* image = NSModuleToImageLoader(module);
1092 if ( image == NULL )
1093 return NULL;
1094 return image->getPath();
1095 }
1096
1097 const char* NSLibraryNameForModule(NSModule module)
1098 {
1099 if ( dyld::gLogAPIs )
1100 dyld::log("%s(%p)\n", __func__, module);
1101 ImageLoader* image = NSModuleToImageLoader(module);
1102 if ( image == NULL )
1103 return NULL;
1104 return image->getPath();
1105 }
1106
1107 bool NSUnLinkModule(NSModule module, uint32_t options)
1108 {
1109 if ( dyld::gLogAPIs )
1110 dyld::log("%s(%p, 0x%08X)\n", __func__, module, options);
1111 if ( module == NULL )
1112 return false;
1113 ImageLoader* image = NSModuleToImageLoader(module);
1114 if ( image == NULL )
1115 return false;
1116 dyld::runImageStaticTerminators(image);
1117 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 13) ) {
1118 __cxa_range_t ranges[image->segmentCount()];
1119 int rangeCount = 0;
1120 for (unsigned int j=0; j < image->segmentCount(); ++j) {
1121 if ( !image->segExecutable(j) )
1122 continue;
1123 ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
1124 ranges[rangeCount].length = image->segSize(j);
1125 ++rangeCount;
1126 }
1127 (*dyld::gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
1128 }
1129 dyld::removeImage(image);
1130
1131 if ( (options & NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED) != 0 )
1132 image->setLeaveMapped();
1133
1134 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1135
1136 // Only delete image if there is no ofi referencing it
1137 // That means the ofi was destroyed after linking, so no one is left to delete this image
1138 const size_t ofiCount = sObjectFileImages.size();
1139 bool found = false;
1140 for (size_t i=0; i < ofiCount; ++i) {
1141 NSObjectFileImage ofi = sObjectFileImages[i];
1142 if ( ofi->image == image )
1143 found = true;
1144 }
1145 if ( !found )
1146 ImageLoader::deleteImage(image);
1147
1148 return true;
1149 }
1150
1151 // internal name and parameters do not match public name and parameters...
1152 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit)
1153 {
1154 if ( dyld::gLogAPIs )
1155 dyld::log("NSLinkEditErrorHandlers()\n");
1156
1157 dyld::registerUndefinedHandler((dyld::UndefinedHandler)undefined);
1158 // no support for multiple or linkedit handlers
1159 }
1160
1161
1162
1163
1164 void NSLinkEditError(NSLinkEditErrors* c, int* errorNumber, const char** fileName, const char** errorString)
1165 {
1166 // FIXME FIXME
1167 *c = sLastErrorFileCode;
1168 *errorNumber = sLastErrorNo;
1169 *fileName = sLastErrorFilePath;
1170 *errorString = dyld::getErrorMessage();
1171 }
1172
1173
1174
1175 static void _dyld_register_binding_handler(void * (*bindingHandler)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions)
1176 {
1177 if ( dyld::gLogAPIs )
1178 dyld::log("%s()\n", __func__);
1179 dyld::gLinkContext.bindingHandler = bindingHandler;
1180 dyld::gLinkContext.bindingOptions = bindingOptions;
1181 }
1182
1183 #endif //DEPRECATED_APIS_SUPPORTED
1184
1185
1186 // Call by fork() in libSystem after the kernel trap is done on the child side
1187 void _dyld_fork_child()
1188 {
1189 if ( dyld::gLogAPIs )
1190 dyld::log("%s()\n", __func__);
1191 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1192 // in libSystem for the child of a fork. But dyld is built with a static copy
1193 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1194 //
1195 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1196 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1197 //
1198 extern mach_port_t mach_task_self_;
1199 mach_task_self_ = task_self_trap();
1200
1201 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1202 // page is not copied on fork. <rdar://problem/6797342>
1203 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1204 dyld::gProcessInfo->coreSymbolicationShmPage = NULL;
1205 // for safety, make sure child starts with clean systemOrderFlag
1206 dyld::gProcessInfo->systemOrderFlag = 0;
1207 }
1208
1209
1210 #if DEPRECATED_APIS_SUPPORTED
1211 // returns true if prebinding was used in main executable
1212 bool _dyld_launched_prebound()
1213 {
1214 if ( dyld::gLogAPIs )
1215 dyld::log("%s()\n", __func__);
1216
1217 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1218 return dyld::mainExecutablePrebound();
1219 }
1220
1221
1222 //
1223 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1224 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1225 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1226 // flag on the image for this module. If the module was found and it was
1227 // private then everything worked and TRUE is returned else FALSE is returned.
1228 //
1229 static bool NSMakePrivateModulePublic(NSModule module)
1230 {
1231 ImageLoader* image = NSModuleToImageLoader(module);
1232 if ( image != NULL ) {
1233 if ( image->hasHiddenExports() ) {
1234 image->setHideExports(false);
1235 return true;
1236 }
1237 }
1238 return false;
1239 }
1240
1241 #endif // DEPRECATED_APIS_SUPPORTED
1242
1243 int _dyld_func_lookup(const char* name, void** address)
1244 {
1245 for (const dyld_func* p = dyld_funcs; p->name != NULL; ++p) {
1246 if ( strcmp(p->name, name) == 0 ) {
1247 if( p->implementation == unimplemented )
1248 dyld::log("unimplemented dyld function: %s\n", p->name);
1249 *address = p->implementation;
1250 return true;
1251 }
1252 }
1253 *address = 0;
1254 return false;
1255 }
1256
1257
1258 static void registerThreadHelpers(const dyld::LibSystemHelpers* helpers)
1259 {
1260 dyld::gLibSystemHelpers = helpers;
1261
1262 #if !SUPPORT_ZERO_COST_EXCEPTIONS
1263 if ( helpers->version >= 5 ) {
1264 // create key use by dyld exception handling
1265 pthread_key_t key;
1266 int result = helpers->pthread_key_create(&key, NULL);
1267 if ( result == 0 )
1268 __Unwind_SjLj_SetThreadKey(key);
1269 }
1270 #endif
1271 }
1272
1273
1274 static void dlerrorClear()
1275 {
1276 if ( dyld::gLibSystemHelpers != NULL ) {
1277 // <rdar://problem/10595338> dlerror buffer leak
1278 // dlerrorClear() should not force allocation, but zero it if already allocated
1279 if ( dyld::gLibSystemHelpers->version >= 10 ) {
1280 if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
1281 return;
1282 }
1283
1284 // first char of buffer is flag whether string (starting at second char) is valid
1285 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
1286 buffer[0] = '\0';
1287 buffer[1] = '\0';
1288 }
1289 }
1290
1291 static void dlerrorSet(const char* msg)
1292 {
1293 if ( dyld::gLibSystemHelpers != NULL ) {
1294 // first char of buffer is flag whether string (starting at second char) is valid
1295 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(strlen(msg)+2);
1296 buffer[0] = '\1';
1297 strcpy(&buffer[1], msg);
1298 }
1299 }
1300
1301
1302 bool dlopen_preflight(const char* path)
1303 {
1304 if ( dyld::gLogAPIs )
1305 dyld::log("%s(%s)\n", __func__, path);
1306
1307 dlerrorClear();
1308
1309 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
1310
1311 const bool leafName = (strchr(path, '/') == NULL);
1312 const bool absolutePath = (path[0] == '/');
1313 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1314 char canonicalPath[PATH_MAX];
1315 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1316 if ( !leafName ) {
1317 // make path canonical if it contains a // or ./
1318 if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
1319 const char* lastSlash = strrchr(path, '/');
1320 char dirPath[PATH_MAX];
1321 if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
1322 dirPath[lastSlash-path] = '\0';
1323 if ( realpath(dirPath, canonicalPath) ) {
1324 strlcat(canonicalPath, "/", sizeof(canonicalPath));
1325 if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
1326 // if all fit in buffer, use new canonical path
1327 path = canonicalPath;
1328 }
1329 }
1330 }
1331 }
1332 }
1333 #endif
1334 #if SUPPORT_ACCELERATE_TABLES
1335 if ( dyld::isPathInCache(path) )
1336 return true;
1337 #endif
1338
1339 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1340 // if requested path is to something in the dyld shared cache, always succeed
1341 if ( dyld::inSharedCache(path) )
1342 return true;
1343
1344 bool result = false;
1345 std::vector<const char*> rpathsFromCallerImage;
1346 try {
1347 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1348 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1349 // for dlopen, use rpath from caller image and from main executable
1350 if ( callerImage != NULL )
1351 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1352 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
1353 if ( callerImage != dyld::mainExecutable() ) {
1354 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1355 }
1356
1357 ImageLoader* image = NULL;
1358 dyld::LoadContext context;
1359 context.useSearchPaths = true;
1360 context.useFallbackPaths= leafName; // a partial path implies don't use fallback paths
1361 context.useLdLibraryPath= leafName; // a leafname implies should search
1362 context.implicitRPath = !absolutePath; // a non-absolute path implies try rpath searching
1363 context.matchByInstallName = true;
1364 context.dontLoad = false;
1365 context.mustBeBundle = false;
1366 context.mustBeDylib = false;
1367 context.canBePIE = true;
1368 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
1369 context.rpath = &callersRPaths; // rpaths from caller and main executable
1370
1371 unsigned cacheIndex;
1372 image = load(path, context, cacheIndex);
1373 if ( image != NULL ) {
1374 dyld::preflight(image, callersRPaths, cacheIndex); // image object deleted by dyld::preflight()
1375 result = true;
1376 }
1377 }
1378 catch (const char* msg) {
1379 const char* str = dyld::mkstringf("dlopen_preflight(%s): %s", path, msg);
1380 dlerrorSet(str);
1381 free((void*)str);
1382 free((void*)msg); // our free() will do nothing if msg is a string literal
1383 }
1384 // free rpaths (getRPaths() malloc'ed each string)
1385 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
1386 const char* str = *it;
1387 free((void*)str);
1388 }
1389 CRSetCrashLogMessage(NULL);
1390 return result;
1391 }
1392
1393 #if SUPPORT_ACCELERATE_TABLES
1394 bool static callerIsNonOSApp(void* callerAddress, const char** shortName)
1395 {
1396 *shortName = NULL;
1397 const mach_header* unusedMh;
1398 const char* unusedPath;
1399 unsigned unusedIndex;
1400 // any address in shared cache is not from app
1401 if ( dyld::addressInCache(callerAddress, &unusedMh, &unusedPath, &unusedIndex) )
1402 return false;
1403
1404 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1405 if ( callerImage == NULL )
1406 return false;
1407
1408 *shortName = callerImage->getShortName();
1409 return ( strncmp(callerImage->getPath(), "/var/containers/", 16) == 0 );
1410 }
1411 #endif
1412
1413 void* dlopen(const char* path, int mode)
1414 {
1415 if ( dyld::gLogAPIs )
1416 dyld::log("%s(%s, 0x%08X)\n", __func__, ((path==NULL) ? "NULL" : path), mode);
1417
1418 #if SUPPORT_ACCELERATE_TABLES
1419 if ( dyld::gLogAppAPIs ) {
1420 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1421 const char* shortName;
1422 if ( callerIsNonOSApp(callerAddress, &shortName) ) {
1423 dyld::log("%s: %s(%s, 0x%08X)\n", shortName, __func__, ((path==NULL) ? "NULL" : path), mode);
1424 }
1425 }
1426 #endif
1427
1428 dlerrorClear();
1429
1430 // passing NULL for path means return magic object
1431 if ( path == NULL ) {
1432 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1433 if ( (mode & RTLD_FIRST) != 0 )
1434 return RTLD_MAIN_ONLY;
1435 else
1436 return RTLD_DEFAULT;
1437 }
1438
1439 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1440 bool lockHeld = false;
1441 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 4) ) {
1442 dyld::gLibSystemHelpers->acquireGlobalDyldLock();
1443 CRSetCrashLogMessage("dyld: in dlopen()");
1444 lockHeld = true;
1445 }
1446
1447 void* result = NULL;
1448 const bool leafName = (strchr(path, '/') == NULL);
1449 const bool absolutePath = (path[0] == '/');
1450 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1451 char canonicalPath[PATH_MAX];
1452 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1453 if ( !leafName ) {
1454 // make path canonical if it contains a // or ./
1455 if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
1456 const char* lastSlash = strrchr(path, '/');
1457 char dirPath[PATH_MAX];
1458 if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
1459 dirPath[lastSlash-path] = '\0';
1460 if ( realpath(dirPath, canonicalPath) ) {
1461 strlcat(canonicalPath, "/", sizeof(canonicalPath));
1462 if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
1463 // if all fit in buffer, use new canonical path
1464 path = canonicalPath;
1465 }
1466 }
1467 }
1468 }
1469 }
1470 #endif
1471 #if SUPPORT_ACCELERATE_TABLES
1472 if ( dyld::dlopenFromCache(path, mode, &result) ) {
1473 // Note: dlopenFromCache() releases the lock
1474 if ( dyld::gLogAPIs )
1475 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1476 return result;
1477 }
1478 #endif
1479
1480 ImageLoader* image = NULL;
1481 std::vector<const char*> rpathsFromCallerImage;
1482 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
1483 try {
1484 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1485 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1486 if ( (mode & RTLD_NOLOAD) == 0 ) {
1487 // for dlopen, use rpath from caller image and from main executable
1488 if ( callerImage != NULL )
1489 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1490 if ( callerImage != dyld::mainExecutable() )
1491 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1492 }
1493
1494 dyld::LoadContext context;
1495 context.useSearchPaths = true;
1496 context.useFallbackPaths= leafName; // a partial path means no fallback paths
1497 context.useLdLibraryPath= leafName; // a leafname implies should search
1498 context.implicitRPath = !absolutePath; // a non-absolute path implies try rpath searching
1499 context.matchByInstallName = true;
1500 context.dontLoad = ( (mode & RTLD_NOLOAD) != 0 );
1501 context.mustBeBundle = false;
1502 context.mustBeDylib = false;
1503 context.canBePIE = true;
1504 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
1505 context.rpath = &callersRPaths; // rpaths from caller and main executable
1506
1507 unsigned cacheIndex;
1508 image = load(path, context, cacheIndex);
1509 #if SUPPORT_ACCELERATE_TABLES
1510 if ( (image != NULL) && (cacheIndex != UINT32_MAX) ) {
1511 // found in cache, but under a different path
1512 const char* betterPath = dyld::getPathFromIndex(cacheIndex);
1513 if ( (betterPath != NULL) && dyld::dlopenFromCache(betterPath, mode, &result) ) {
1514 // Note: dlopenFromCache() releases the lock
1515 if ( dyld::gLogAPIs )
1516 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1517 return result;
1518 }
1519 }
1520 #endif
1521 if ( image != NULL ) {
1522 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1523 // this image is not garbage collected
1524 image->incrementDlopenReferenceCount();
1525 // link in all dependents
1526 if ( (mode & RTLD_NOLOAD) == 0 ) {
1527 bool alreadyLinked = image->isLinked();
1528 bool forceLazysBound = ( (mode & RTLD_NOW) != 0 );
1529 dyld::link(image, forceLazysBound, false, callersRPaths, cacheIndex);
1530 if ( ! alreadyLinked ) {
1531 // only hide exports if image is not already in use
1532 if ( (mode & RTLD_LOCAL) != 0 )
1533 image->setHideExports(true);
1534 }
1535 }
1536
1537 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1538 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1539 // The subtle differences are:
1540 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1541 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1542 if ( (mode & RTLD_NODELETE) != 0 )
1543 image->setLeaveMapped();
1544
1545 // release global dyld lock early, this enables initializers to do threaded operations
1546 if ( lockHeld ) {
1547 CRSetCrashLogMessage(NULL);
1548 dyld::gLibSystemHelpers->releaseGlobalDyldLock();
1549 lockHeld = false;
1550 }
1551
1552 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1553 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1554 // called from within an initializer because it can cause initializers to run
1555 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1556 // to run, then don't use RTLD_NOLOAD.
1557 if ( (mode & RTLD_NOLOAD) == 0 ) {
1558 // run initializers
1559 dyld::runInitializers(image);
1560 }
1561
1562 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1563 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1564 if ( (mode & RTLD_FIRST) != 0 )
1565 result = (void*)(((uintptr_t)image)|1);
1566 else
1567 result = image;
1568 }
1569 }
1570 catch (const char* msg) {
1571 if ( image != NULL ) {
1572 // load() succeeded but, link() failed
1573 // back down reference count and do GC
1574 image->decrementDlopenReferenceCount();
1575 if ( image->dlopenCount() == 0 )
1576 dyld::garbageCollectImages();
1577 }
1578 const char* str = dyld::mkstringf("dlopen(%s, %d): %s", path, mode, msg);
1579 if ( dyld::gLogAPIs )
1580 dyld::log(" %s() failed, error: '%s'\n", __func__, str);
1581 dlerrorSet(str);
1582 free((void*)str);
1583 free((void*)msg); // our free() will do nothing if msg is a string literal
1584 result = NULL;
1585 }
1586 // free rpaths (getRPaths() malloc'ed each string)
1587 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
1588 const char* str = *it;
1589 free((void*)str);
1590 }
1591
1592 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1593 if ( (mode & RTLD_NOLOAD) && (result == NULL) ) {
1594 dlerrorSet("image not already loaded");
1595 }
1596
1597 if ( lockHeld ) {
1598 CRSetCrashLogMessage(NULL);
1599 dyld::gLibSystemHelpers->releaseGlobalDyldLock();
1600 }
1601 if ( dyld::gLogAPIs && (result != NULL) )
1602 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1603 return result;
1604 }
1605
1606
1607
1608 int dlclose(void* handle)
1609 {
1610 if ( dyld::gLogAPIs )
1611 dyld::log("%s(%p)\n", __func__, handle);
1612
1613 // silently accept magic handles for main executable
1614 if ( handle == RTLD_MAIN_ONLY )
1615 return 0;
1616 if ( handle == RTLD_DEFAULT )
1617 return 0;
1618
1619 ImageLoader* image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
1620 if ( dyld::validImage(image) ) {
1621 dlerrorClear();
1622 // decrement use count
1623 if ( image->decrementDlopenReferenceCount() ) {
1624 dlerrorSet("dlclose() called too many times");
1625 return -1;
1626 }
1627 // remove image if reference count went to zero
1628 if ( image->dlopenCount() == 0 )
1629 dyld::garbageCollectImages();
1630 return 0;
1631 }
1632 else {
1633 dlerrorSet("invalid handle passed to dlclose()");
1634 return -1;
1635 }
1636 }
1637
1638
1639
1640 int dladdr(const void* address, Dl_info* info)
1641 {
1642 if ( dyld::gLogAPIs )
1643 dyld::log("%s(%p, %p)\n", __func__, address, info);
1644
1645 CRSetCrashLogMessage("dyld: in dladdr()");
1646 #if SUPPORT_ACCELERATE_TABLES
1647 if ( dyld::dladdrFromCache(address, info) ) {
1648 CRSetCrashLogMessage(NULL);
1649 return 1; // success
1650 }
1651 #endif
1652
1653 ImageLoader* image = dyld::findImageContainingAddress(address);
1654 if ( image != NULL ) {
1655 info->dli_fname = image->getRealPath();
1656 info->dli_fbase = (void*)image->machHeader();
1657 if ( address == info->dli_fbase ) {
1658 // special case lookup of header
1659 info->dli_sname = "__dso_handle";
1660 info->dli_saddr = info->dli_fbase;
1661 CRSetCrashLogMessage(NULL);
1662 return 1; // success
1663 }
1664 // find closest symbol in the image
1665 info->dli_sname = image->findClosestSymbol(address, (const void**)&info->dli_saddr);
1666 // never return the mach_header symbol
1667 if ( info->dli_saddr == info->dli_fbase ) {
1668 info->dli_sname = NULL;
1669 info->dli_saddr = NULL;
1670 CRSetCrashLogMessage(NULL);
1671 return 1; // success
1672 }
1673 if ( info->dli_sname != NULL ) {
1674 if ( info->dli_sname[0] == '_' )
1675 info->dli_sname = info->dli_sname +1; // strip off leading underscore
1676 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1677 CRSetCrashLogMessage(NULL);
1678 return 1; // success
1679 }
1680 info->dli_sname = NULL;
1681 info->dli_saddr = NULL;
1682 CRSetCrashLogMessage(NULL);
1683 return 1; // success
1684 }
1685 CRSetCrashLogMessage(NULL);
1686 return 0; // failure
1687 }
1688
1689
1690 char* dlerror()
1691 {
1692 if ( dyld::gLogAPIs )
1693 dyld::log("%s()\n", __func__);
1694
1695 if ( dyld::gLibSystemHelpers != NULL ) {
1696 // if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
1697 if ( dyld::gLibSystemHelpers->version >= 10 ) {
1698 if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
1699 return NULL;
1700 }
1701
1702 // first char of buffer is flag whether string (starting at second char) is valid
1703 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
1704 if ( buffer[0] != '\0' ) { // if valid buffer
1705 buffer[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1706 return &buffer[1]; // return message
1707 }
1708 }
1709 return NULL;
1710 }
1711
1712 void* dlsym(void* handle, const char* symbolName)
1713 {
1714 if ( dyld::gLogAPIs )
1715 dyld::log("%s(%p, %s)\n", __func__, handle, symbolName);
1716
1717 #if SUPPORT_ACCELERATE_TABLES
1718 if ( dyld::gLogAppAPIs ) {
1719 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1720 const char* shortName;
1721 if ( callerIsNonOSApp(callerAddress, &shortName) ) {
1722 dyld::log("%s: %s(%p, %s)\n", shortName, __func__, handle, symbolName);
1723 }
1724 }
1725 #endif
1726
1727 CRSetCrashLogMessage("dyld: in dlsym()");
1728 dlerrorClear();
1729
1730 const ImageLoader* image;
1731 const ImageLoader::Symbol* sym;
1732 void* result;
1733
1734 // dlsym() assumes symbolName passed in is same as in C source code
1735 // dyld assumes all symbol names have an underscore prefix
1736 char underscoredName[strlen(symbolName)+2];
1737 underscoredName[0] = '_';
1738 strcpy(&underscoredName[1], symbolName);
1739
1740 // magic "search all" handle
1741 if ( handle == RTLD_DEFAULT ) {
1742 if ( dyld::flatFindExportedSymbol(underscoredName, &sym, &image) ) {
1743 CRSetCrashLogMessage(NULL);
1744 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, NULL, false, underscoredName);
1745 if ( dyld::gLogAPIs )
1746 dyld::log(" %s(RTLD_DEFAULT, %s) ==> %p\n", __func__, symbolName, result);
1747 return result;
1748 }
1749 const char* str = dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName);
1750 dlerrorSet(str);
1751 free((void*)str);
1752 CRSetCrashLogMessage(NULL);
1753 if ( dyld::gLogAPIs )
1754 dyld::log(" %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__, symbolName);
1755 return NULL;
1756 }
1757
1758 // magic "search only main executable" handle
1759 else if ( handle == RTLD_MAIN_ONLY ) {
1760 image = dyld::mainExecutable();
1761 sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
1762 if ( sym != NULL ) {
1763 CRSetCrashLogMessage(NULL);
1764 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, NULL, false, underscoredName);
1765 if ( dyld::gLogAPIs )
1766 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__, symbolName, result);
1767 return result;
1768 }
1769 const char* str = dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName);
1770 dlerrorSet(str);
1771 free((void*)str);
1772 CRSetCrashLogMessage(NULL);
1773 if ( dyld::gLogAPIs )
1774 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__, symbolName);
1775 return NULL;
1776 }
1777
1778 // magic "search what I would see" handle
1779 else if ( handle == RTLD_NEXT ) {
1780 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1781 #if SUPPORT_ACCELERATE_TABLES
1782 const mach_header* mh;
1783 const char* path;
1784 unsigned index;
1785 if ( dyld::addressInCache(callerAddress, &mh, &path, &index) ) {
1786 // if dylib in cache is calling dlsym(RTLD_NEXT,xxx) handle search differently
1787 result = dyld::dlsymFromCache(RTLD_NEXT, underscoredName, index);
1788 if ( dyld::gLogAPIs )
1789 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__, symbolName, result);
1790 return result;
1791 }
1792 #endif
1793 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1794 sym = callerImage->findExportedSymbolInDependentImages(underscoredName, dyld::gLinkContext, &image); // don't search image, but do search what it links against
1795 if ( sym != NULL ) {
1796 CRSetCrashLogMessage(NULL);
1797 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext , callerImage, false, underscoredName);
1798 if ( dyld::gLogAPIs )
1799 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__, symbolName, result);
1800 return result;
1801 }
1802 const char* str = dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName);
1803 dlerrorSet(str);
1804 free((void*)str);
1805 CRSetCrashLogMessage(NULL);
1806 if ( dyld::gLogAPIs )
1807 dyld::log(" %s(RTLD_NEXT, %s) ==> NULL\n", __func__, symbolName);
1808 return NULL;
1809 }
1810 // magic "search me, then what I would see" handle
1811 else if ( handle == RTLD_SELF ) {
1812 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1813 #if SUPPORT_ACCELERATE_TABLES
1814 const mach_header* mh;
1815 const char* path;
1816 unsigned index;
1817 if ( dyld::addressInCache(callerAddress, &mh, &path, &index) ) {
1818 // if dylib in cache is calling dlsym(RTLD_SELF,xxx) handle search differently
1819 result = dyld::dlsymFromCache(RTLD_SELF, underscoredName, index);
1820 if ( dyld::gLogAPIs )
1821 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__, symbolName, result);
1822 return result;
1823 }
1824 #endif
1825 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1826 sym = callerImage->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
1827 if ( sym != NULL ) {
1828 CRSetCrashLogMessage(NULL);
1829 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage, false, underscoredName);
1830 if ( dyld::gLogAPIs )
1831 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__, symbolName, result);
1832 return result;
1833 }
1834 const char* str = dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName);
1835 dlerrorSet(str);
1836 free((void*)str);
1837 CRSetCrashLogMessage(NULL);
1838 if ( dyld::gLogAPIs )
1839 dyld::log(" %s(RTLD_SELF, %s) ==> NULL\n", __func__, symbolName);
1840 return NULL;
1841 }
1842 #if SUPPORT_ACCELERATE_TABLES
1843 // check for mega dylib handle
1844 else if ( dyld::isCacheHandle(handle) ) {
1845 result = dyld::dlsymFromCache(handle, underscoredName, 0);
1846 if ( dyld::gLogAPIs )
1847 dyld::log(" %s(%p, %s) ==> %p\n", __func__, handle, symbolName, result);
1848 return result;
1849 }
1850 #endif
1851 // real handle
1852 image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
1853 if ( dyld::validImage(image) ) {
1854 if ( (((uintptr_t)handle) & 1) != 0 )
1855 sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
1856 else
1857 sym = image->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
1858
1859 if ( sym != NULL ) {
1860 CRSetCrashLogMessage(NULL);
1861 ImageLoader* callerImage = NULL;
1862 if ( sDynamicInterposing ) {
1863 // only take time to look up caller, if dynamic interposing in use
1864 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
1865 callerImage = dyld::findImageContainingAddress(callerAddress);
1866 }
1867 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage, false, underscoredName);
1868 if ( dyld::gLogAPIs )
1869 dyld::log(" %s(%p, %s) ==> %p\n", __func__, handle, symbolName, result);
1870 return result;
1871 }
1872 const char* str = dyld::mkstringf("dlsym(%p, %s): symbol not found", handle, symbolName);
1873 dlerrorSet(str);
1874 free((void*)str);
1875 }
1876 else {
1877 dlerrorSet("invalid handle passed to dlsym()");
1878 }
1879 CRSetCrashLogMessage(NULL);
1880 if ( dyld::gLogAPIs )
1881 dyld::log(" %s(%p, %s) ==> NULL\n", __func__, handle, symbolName);
1882 return NULL;
1883 }
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894 const struct dyld_all_image_infos* _dyld_get_all_image_infos()
1895 {
1896 return dyld::gProcessInfo;
1897 }
1898
1899
1900 #if SUPPORT_ZERO_COST_EXCEPTIONS
1901 static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info)
1902 {
1903 //if ( dyld::gLogAPIs )
1904 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
1905
1906 #if SUPPORT_ACCELERATE_TABLES
1907 if ( dyld::findUnwindSections(addr, info) )
1908 return true;
1909 #endif
1910 ImageLoader* image = dyld::findImageContainingAddress(addr);
1911 if ( image != NULL ) {
1912 image->getUnwindInfo(info);
1913 return true;
1914 }
1915 return false;
1916 }
1917 #endif
1918
1919
1920 const char* dyld_image_path_containing_address(const void* address)
1921 {
1922 if ( dyld::gLogAPIs )
1923 dyld::log("%s(%p)\n", __func__, address);
1924
1925 #if SUPPORT_ACCELERATE_TABLES
1926 const mach_header* mh;
1927 const char* path;
1928 if ( dyld::addressInCache(address, &mh, &path) )
1929 return path;
1930 #endif
1931
1932 ImageLoader* image = dyld::findImageContainingAddress(address);
1933 if ( image != NULL )
1934 return image->getRealPath();
1935 return NULL;
1936 }
1937
1938
1939
1940 bool dyld_shared_cache_some_image_overridden()
1941 {
1942 return dyld::gSharedCacheOverridden;
1943 }
1944
1945
1946 void dyld_dynamic_interpose(const struct mach_header* mh, const struct dyld_interpose_tuple array[], size_t count)
1947 {
1948 if ( mh == NULL )
1949 return;
1950 if ( array == NULL )
1951 return;
1952 if ( count == 0 )
1953 return;
1954 ImageLoader* image = dyld::findImageByMachHeader(mh);
1955 if ( image == NULL )
1956 return;
1957
1958 // make pass at bound references in this image and update them
1959 dyld::gLinkContext.dynamicInterposeArray = array;
1960 dyld::gLinkContext.dynamicInterposeCount = count;
1961 image->dynamicInterpose(dyld::gLinkContext);
1962 dyld::gLinkContext.dynamicInterposeArray = NULL;
1963 dyld::gLinkContext.dynamicInterposeCount = 0;
1964
1965 // leave interposing info so any future (lazy) binding will get it too
1966 image->addDynamicInterposingTuples(array, count);
1967
1968 sDynamicInterposing = true;
1969 }
1970
1971
1972 bool _dyld_is_memory_immutable(const void* addr, size_t length)
1973 {
1974 if ( dyld::gLogAPIs )
1975 dyld::log("%s(%p, %ld)\n", __func__, addr, length);
1976
1977 uintptr_t checkStart = (uintptr_t)addr;
1978 uintptr_t checkEnd = checkStart + length;
1979
1980 // quick check to see if in r/o region of shared cache. If so return true.
1981 const DyldSharedCache* cache = (DyldSharedCache*)dyld::imMemorySharedCacheHeader();
1982 if ( cache != nullptr ) {
1983 const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)((char*)cache + cache->header.mappingOffset);
1984 uintptr_t roStart = (uintptr_t)cache;
1985 uintptr_t roEnd = roStart + (uintptr_t)mappings[0].size;
1986 if ( (roStart < checkStart) && (checkEnd < roEnd) )
1987 return true;
1988 }
1989
1990 // Otherwise find if addr is in a dyld loaded image
1991 ImageLoader* image = dyld::findImageContainingAddress(addr);
1992 if ( image != NULL ) {
1993 // <rdar://problem/24091154> already checked for r/o portion of cache
1994 if ( image->inSharedCache() )
1995 return false;
1996 if ( !image->neverUnload() )
1997 return false;
1998 for (unsigned i=0, e=image->segmentCount(); i < e; ++i) {
1999 if ( (image->segActualLoadAddress(i) < checkStart) && (checkEnd < image->segActualEndAddress(i)) ) {
2000 return !image->segWriteable(i);
2001 }
2002 }
2003 }
2004 return false;
2005 }
2006
2007
2008
2009 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped,
2010 _dyld_objc_notify_init init,
2011 _dyld_objc_notify_unmapped unmapped)
2012 {
2013 dyld::registerObjCNotifiers(mapped, init, unmapped);
2014 }
2015
2016
2017 bool _dyld_get_shared_cache_uuid(uuid_t uuid)
2018 {
2019 return dyld::sharedCacheUUID(uuid);
2020 }
2021
2022 const void* _dyld_get_shared_cache_range(size_t* length)
2023 {
2024 const DyldSharedCache* cache = (DyldSharedCache*)dyld::imMemorySharedCacheHeader();
2025 if ( cache != nullptr ) {
2026 const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)((char*)cache + cache->header.mappingOffset);
2027 *length = (size_t)((mappings[2].address + mappings[2].size) - mappings[0].address);
2028 return cache;
2029 }
2030 return nullptr;
2031 }
2032
2033
2034