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