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