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