]> git.saurik.com Git - apple/dyld.git/blobdiff - src/dyldAPIs.cpp
dyld-360.18.tar.gz
[apple/dyld.git] / src / dyldAPIs.cpp
index 64cfb890ca56e5bbf27e2da6194587e22edee520..b64331a3e4d04c3b620b51053988b78b8410717e 100644 (file)
@@ -1,6 +1,6 @@
 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
  *
- * Copyright (c) 2004-2005 Apple Computer, Inc. All rights reserved.
+ * Copyright (c) 2004-2009 Apple Inc. All rights reserved.
  *
  * @APPLE_LICENSE_HEADER_START@
  * 
 //
 //
 
-
+#define __STDC_LIMIT_MACROS
 #include <stddef.h>
-#include <stdio.h>
+#include <stdint.h>
 #include <string.h>
+#include <sys/param.h>
+#include <sys/mount.h>
+#include <Availability.h>
+
+
+#include <vector>
+#include <map>
+#include <algorithm>
+
 #include <mach/mach.h>
 #include <sys/time.h>
 #include <sys/sysctl.h>
+#include <mach/mach_traps.h> // for task_self_trap()
 
-extern "C" mach_port_name_t    task_self_trap(void);  // can't include <System/mach/mach_traps.h> because it is missing extern C
 
-#include "mach-o/dyld_gdb.h"
+#include "mach-o/dyld_images.h"
 #include "mach-o/dyld.h"
 #include "mach-o/dyld_priv.h"
-#include "dlfcn.h"
 
 #include "ImageLoader.h"
 #include "dyld.h"
-#include "dyldLibSystemThreadHelpers.h"
+#include "dyldLibSystemInterface.h"
+
+#undef _POSIX_C_SOURCE
+#include "dlfcn.h"
 
+// from dyldExceptions.c
+extern "C" void __Unwind_SjLj_SetThreadKey(pthread_key_t key);
+
+// from dyld_gdb.cpp 
+extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
+
+// deprecated APIs are still availble on Mac OS X, but not on iPhone OS
+#if __IPHONE_OS_VERSION_MIN_REQUIRED   
+       #define DEPRECATED_APIS_SUPPORTED 0
+#else
+       #define DEPRECATED_APIS_SUPPORTED 1
+#endif
+
+static bool sDynamicInterposing = false;
+
+#if DEPRECATED_APIS_SUPPORTED
 static char sLastErrorFilePath[1024];
 static NSLinkEditErrors sLastErrorFileCode;
 static int sLastErrorNo;
-
+#endif
 
 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
 // This conditional keeps support for old libSystem's which needed some help implementing the API's
-#define OLD_LIBSYSTEM_SUPPORT 1
-
+#define OLD_LIBSYSTEM_SUPPORT (__i386__)
 
 // The following functions have no prototype in any header.  They are special cases
 // where _dyld_func_lookup() is used directly.
+static void _dyld_make_delayed_module_initializer_calls();
+static void registerThreadHelpers(const dyld::LibSystemHelpers*);
+#if DEPRECATED_APIS_SUPPORTED
 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit);
+#if OLD_LIBSYSTEM_SUPPORT
 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options);
+#endif
 static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions);
-static void _dyld_fork_prepare();
-static void _dyld_fork_parent();
-static void _dyld_fork_child();
-static void _dyld_fork_child_final();
-static void _dyld_make_delayed_module_initializer_calls();
-static void _dyld_mod_term_funcs();
 static bool NSMakePrivateModulePublic(NSModule module);
 static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header);
-static void registerThreadHelpers(const dyld::ThreadingHelpers*);
-static void _dyld_update_prebinding(int pathCount, const char* paths[], uint32_t flags);
-static const struct dyld_all_image_infos* _dyld_get_all_image_infos();
 
 // The following functions are dyld API's, but since dyld links with a static copy of libc.a
 // the public name cannot be used.
 static void            client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module);
 static bool            client_NSIsSymbolNameDefined(const char* symbolName);
-
+#endif // DEPRECATED_APIS_SUPPORTED
+#if SUPPORT_ZERO_COST_EXCEPTIONS
+static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info);
+#endif
 
 static void unimplemented()
 {
@@ -91,38 +116,54 @@ struct dyld_func {
 };
 
 static struct dyld_func dyld_funcs[] = {
-    {"__dyld_image_count",                                                     (void*)_dyld_image_count },
-    {"__dyld_get_image_header",                                                (void*)_dyld_get_image_header },
-    {"__dyld_get_image_vmaddr_slide",                          (void*)_dyld_get_image_vmaddr_slide },
-    {"__dyld_get_image_name",                                          (void*)_dyld_get_image_name },
+    {"__dyld_register_func_for_add_image",                             (void*)_dyld_register_func_for_add_image },
+    {"__dyld_register_func_for_remove_image",                  (void*)_dyld_register_func_for_remove_image },
+    {"__dyld_dladdr",                                                                  (void*)dladdr },
+    {"__dyld_dlclose",                                                                 (void*)dlclose },
+    {"__dyld_dlerror",                                                                 (void*)dlerror },
+    {"__dyld_dlopen",                                                                  (void*)dlopen },
+    {"__dyld_dlsym",                                                                   (void*)dlsym },
+    {"__dyld_dlopen_preflight",                                                        (void*)dlopen_preflight },
+       {"__dyld_image_count",                                                          (void*)_dyld_image_count },
+    {"__dyld_get_image_header",                                                        (void*)_dyld_get_image_header },
+    {"__dyld_get_image_vmaddr_slide",                                  (void*)_dyld_get_image_vmaddr_slide },
+    {"__dyld_get_image_name",                                                  (void*)_dyld_get_image_name },
+    {"__dyld_get_image_slide",                                                 (void*)_dyld_get_image_slide },
+    {"__dyld__NSGetExecutablePath",                                            (void*)_NSGetExecutablePath },
+
+       // SPIs
+       {"__dyld_dyld_register_image_state_change_handler",     (void*)dyld_register_image_state_change_handler },
+       {"__dyld_register_thread_helpers",                                      (void*)registerThreadHelpers },
+       {"__dyld_fork_child",                                                           (void*)_dyld_fork_child },
+    {"__dyld_make_delayed_module_initializer_calls",   (void*)_dyld_make_delayed_module_initializer_calls },
+       {"__dyld_get_all_image_infos",                                          (void*)_dyld_get_all_image_infos },
+#if SUPPORT_ZERO_COST_EXCEPTIONS
+       {"__dyld_find_unwind_sections",                                         (void*)client_dyld_find_unwind_sections },
+#endif
+#if __i386__ || __x86_64__ || __arm__ || __arm64__
+       {"__dyld_fast_stub_entry",                                                      (void*)dyld::fastBindLazySymbol },
+#endif
+       {"__dyld_image_path_containing_address",                        (void*)dyld_image_path_containing_address },
+       {"__dyld_shared_cache_some_image_overridden",           (void*)dyld_shared_cache_some_image_overridden },
+       {"__dyld_process_is_restricted",                                        (void*)dyld::processIsRestricted },
+       {"__dyld_dynamic_interpose",                                            (void*)dyld_dynamic_interpose },
+#if DYLD_SHARED_CACHE_SUPPORT
+       {"__dyld_shared_cache_file_path",                                       (void*)dyld::getStandardSharedCacheFilePath },
+#endif
+    {"__dyld_get_image_header_containing_address",             (void*)dyld_image_header_containing_address },
+
+       // deprecated
+#if DEPRECATED_APIS_SUPPORTED
     {"__dyld_lookup_and_bind",                                         (void*)client_dyld_lookup_and_bind },
     {"__dyld_lookup_and_bind_with_hint",                       (void*)_dyld_lookup_and_bind_with_hint },
-    {"__dyld_lookup_and_bind_objc",                                    (void*)unimplemented },
     {"__dyld_lookup_and_bind_fully",                           (void*)_dyld_lookup_and_bind_fully },
     {"__dyld_install_handlers",                                                (void*)_dyld_install_handlers },
     {"__dyld_link_edit_error",                                         (void*)NSLinkEditError },
-#if OLD_LIBSYSTEM_SUPPORT
-    {"__dyld_link_module",                                                     (void*)_dyld_link_module },
-#endif
     {"__dyld_unlink_module",                                           (void*)NSUnLinkModule },
-    {"__dyld_register_func_for_add_image",                     (void*)_dyld_register_func_for_add_image },
-    {"__dyld_register_func_for_remove_image",          (void*)_dyld_register_func_for_remove_image },
-    {"__dyld_register_func_for_link_module",           (void*)unimplemented },
-    {"__dyld_register_func_for_unlink_module",         (void*)unimplemented },
-    {"__dyld_register_func_for_replace_module",                (void*)unimplemented },
-    {"__dyld_get_objc_module_sect_for_module",         (void*)unimplemented },
     {"__dyld_bind_objc_module",                                                (void*)_dyld_bind_objc_module },
     {"__dyld_bind_fully_image_containing_address",  (void*)_dyld_bind_fully_image_containing_address },
     {"__dyld_image_containing_address",                                (void*)_dyld_image_containing_address },
-    {"__dyld_get_image_header_containing_address",  (void*)_dyld_get_image_header_containing_address },
-    {"__dyld_moninit",                                                         (void*)_dyld_moninit },
-    {"__dyld_register_binding_handler",                                                (void*)_dyld_register_binding_handler },
-    {"__dyld_fork_prepare",                                                    (void*)_dyld_fork_prepare },
-    {"__dyld_fork_parent",                                                     (void*)_dyld_fork_parent },
-    {"__dyld_fork_child",                                                      (void*)_dyld_fork_child },
-    {"__dyld_fork_child_final",                                                (void*)_dyld_fork_child_final },
-    {"__dyld_fork_mach_init",                                          (void*)unimplemented },
-    {"__dyld_make_delayed_module_initializer_calls",(void*)_dyld_make_delayed_module_initializer_calls },
+    {"__dyld_register_binding_handler",                                (void*)_dyld_register_binding_handler },
     {"__dyld_NSNameOfSymbol",                                          (void*)NSNameOfSymbol },
     {"__dyld_NSAddressOfSymbol",                                       (void*)NSAddressOfSymbol },
     {"__dyld_NSModuleForSymbol",                                       (void*)NSModuleForSymbol },
@@ -139,15 +180,11 @@ static struct dyld_func dyld_funcs[] = {
     {"__dyld_NSAddLibrary",                                                    (void*)NSAddLibrary },
     {"__dyld_NSAddLibraryWithSearching",                       (void*)NSAddLibraryWithSearching },
     {"__dyld_NSAddImage",                                                      (void*)NSAddImage },
-    {"__dyld__NSGetExecutablePath",                                    (void*)_NSGetExecutablePath },
     {"__dyld_launched_prebound",                                       (void*)_dyld_launched_prebound },
     {"__dyld_all_twolevel_modules_prebound",           (void*)_dyld_all_twolevel_modules_prebound },
     {"__dyld_call_module_initializers_for_dylib",   (void*)_dyld_call_module_initializers_for_dylib },
-    {"__dyld_mod_term_funcs",                                          (void*)_dyld_mod_term_funcs },
-    {"__dyld_install_link_edit_symbol_handlers",       (void*)dyld::registerZeroLinkHandlers },
     {"__dyld_NSCreateObjectFileImageFromFile",                 (void*)NSCreateObjectFileImageFromFile },
     {"__dyld_NSCreateObjectFileImageFromMemory",               (void*)NSCreateObjectFileImageFromMemory },
-    {"__dyld_NSCreateCoreFileImageFromFile",                   (void*)unimplemented },
     {"__dyld_NSDestroyObjectFileImage",                                        (void*)NSDestroyObjectFileImage },
     {"__dyld_NSLinkModule",                                                            (void*)NSLinkModule },
     {"__dyld_NSHasModInitObjectFileImage",                             (void*)NSHasModInitObjectFileImage },
@@ -157,20 +194,24 @@ static struct dyld_func dyld_funcs[] = {
     {"__dyld_NSSymbolReferenceNameInObjectFileImage",  (void*)NSSymbolReferenceNameInObjectFileImage },
     {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage },
     {"__dyld_NSGetSectionDataInObjectFileImage",               (void*)NSGetSectionDataInObjectFileImage },
-    {"__dyld_NSFindSectionAndOffsetInObjectFileImage",  (void*)NSFindSectionAndOffsetInObjectFileImage },
-       {"__dyld_register_thread_helpers",                                      (void*)registerThreadHelpers },
-    {"__dyld_dladdr",                                                                  (void*)dladdr },
-    {"__dyld_dlclose",                                                                 (void*)dlclose },
-    {"__dyld_dlerror",                                                                 (void*)dlerror },
-    {"__dyld_dlopen",                                                                  (void*)dlopen },
-    {"__dyld_dlsym",                                                                   (void*)dlsym },
-       {"__dyld_update_prebinding",                                            (void*)_dyld_update_prebinding },
-       {"__dyld_get_all_image_infos",                                          (void*)_dyld_get_all_image_infos },
+#if OLD_LIBSYSTEM_SUPPORT
+    {"__dyld_link_module",                                                     (void*)_dyld_link_module },
+#endif
+#endif //DEPRECATED_APIS_SUPPORTED
+
     {NULL, 0}
 };
 
 
 
+#if DEPRECATED_APIS_SUPPORTED
+
+static void dyldAPIhalt(const char* apiName, const char* errorMsg)
+{
+       dyld::log("dyld: %s() error\n", apiName);
+       dyld::halt(errorMsg);
+}
+
 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
 inline NSSymbol SymbolToNSSymbol(const ImageLoader::Symbol* sym)
 {
@@ -182,7 +223,7 @@ inline const ImageLoader::Symbol* NSSymbolToSymbol(NSSymbol sym)
 }      
 
 // dyld's abstract type NSModule is implemented as ImageLoader*
-inline NSModule ImageLoaderToNSModule(ImageLoader* image)
+inline NSModule ImageLoaderToNSModule(const ImageLoader* image)
 {
        return (NSModule)image;
 }      
@@ -201,6 +242,9 @@ struct __NSObjectFileImage
        const void*             imageBaseAddress;       // not used with OFI created from files
        size_t                  imageLength;            // not used with OFI created from files
 };
+
+
+VECTOR_NEVER_DESTRUCTED(NSObjectFileImage);
 static std::vector<NSObjectFileImage> sObjectFileImages;
 
 
@@ -213,13 +257,6 @@ static std::vector<NSObjectFileImage> sObjectFileImages;
 //
 
 
-static void dyldAPIhalt(const char* apiName, const char* errorMsg)
-{
-       fprintf(stderr, "dyld: %s() error\n", apiName);
-       dyld::halt(errorMsg);
-}
-
-
 
 static void setLastError(NSLinkEditErrors code, int errnum, const char* file, const char* message)
 {
@@ -230,6 +267,7 @@ static void setLastError(NSLinkEditErrors code, int errnum, const char* file, co
        sLastErrorNo = errnum;
 }
 
+#endif // DEPRECATED_APIS_SUPPORTED
 
 /*
  *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
@@ -244,16 +282,110 @@ static void setLastError(NSLinkEditErrors code, int errnum, const char* file, co
 int _NSGetExecutablePath(char* buf, uint32_t *bufsize)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(...)\n", __func__);
+               dyld::log("%s(...)\n", __func__);
        const char* exePath = dyld::getExecutablePath();
        if(*bufsize < strlen(exePath) + 1){
-           *bufsize = strlen(exePath) + 1;
+           *bufsize = (uint32_t)(strlen(exePath) + 1);
            return -1;
        }
        strcpy(buf, exePath);
        return 0;
 }
 
+uint32_t _dyld_image_count(void)
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s()\n", __func__);
+       return dyld::getImageCount();
+}
+
+const struct mach_header* _dyld_get_image_header(uint32_t image_index)
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%u)\n", __func__, image_index);
+       ImageLoader* image = dyld::getIndexedImage(image_index);
+       if ( image != NULL )
+               return (struct mach_header*)image->machHeader();
+       else
+               return NULL;
+}
+
+intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index)
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%u)\n", __func__, image_index);
+       ImageLoader* image = dyld::getIndexedImage(image_index);
+       if ( image != NULL )
+               return image->getSlide();
+       else
+               return 0;
+}
+
+intptr_t _dyld_get_image_slide(const struct mach_header* mh)
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%p)\n", __func__, mh);
+       ImageLoader* image = dyld::findImageByMachHeader(mh);
+       if ( image != NULL )
+               return image->getSlide();
+       else
+               return 0;
+}
+
+
+const char* _dyld_get_image_name(uint32_t image_index)
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%u)\n", __func__, image_index);
+       ImageLoader* image = dyld::getIndexedImage(image_index);
+       if ( image != NULL )
+               return image->getRealPath();
+       else
+               return NULL;
+}
+
+const struct mach_header * dyld_image_header_containing_address(const void* address)
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%p)\n", __func__, address);
+       ImageLoader* image = dyld::findImageContainingAddress(address);
+       if ( image != NULL ) 
+               return image->machHeader();
+       return NULL;
+}
+
+
+void _dyld_register_func_for_add_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%p)\n", __func__, (void *)func);
+       dyld::registerAddCallback(func);
+}
+
+void _dyld_register_func_for_remove_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%p)\n", __func__, (void *)func);
+       dyld::registerRemoveCallback(func);
+}
+
+
+
+// called by crt before main() by programs linked with 10.4 or earlier crt1.o
+static void _dyld_make_delayed_module_initializer_calls()
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s()\n", __func__);
+               
+#if SUPPORT_OLD_CRT_INITIALIZATION
+       if ( dyld::gRunInitializersOldWay )
+               dyld::initializeMainExecutable();
+#endif
+}
+
+
+
+#if DEPRECATED_APIS_SUPPORTED
 
 //
 // _dyld_call_module_initializers_for_dylib() is the dyld side of
@@ -267,7 +399,7 @@ int _NSGetExecutablePath(char* buf, uint32_t *bufsize)
 static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "__initialize_Cplusplus()\n");
+               dyld::log("__initialize_Cplusplus()\n");
        
        // for now, do nothing...
 }
@@ -276,15 +408,15 @@ static void _dyld_call_module_initializers_for_dylib(const struct mach_header* m
 void _dyld_lookup_and_bind_fully(const char* symbolName, void** address, NSModule* module)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\", %p, %p)\n", __func__, symbolName, address, module);
+               dyld::log("%s(\"%s\", %p, %p)\n", __func__, symbolName, address, module);
        ImageLoader* image;
        const ImageLoader::Symbol* sym;
        dyld::clearErrorMessage();
-       if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) { 
+       if ( dyld::flatFindExportedSymbol(symbolName, &sym, (const ImageLoader**)&image) ) {    
                try {
-                       dyld::link(image, ImageLoader::kLazyOnly, ImageLoader::kDontRunInitializers);
+                       image->bindAllLazyPointers(dyld::gLinkContext, true);
                        if ( address != NULL)
-                               *address = (void*)image->getExportedSymbolAddress(sym);
+                               *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
                        if ( module != NULL)
                                *module = ImageLoaderToNSModule(image);
                }
@@ -306,12 +438,12 @@ void _dyld_lookup_and_bind_fully(const char* symbolName, void** address, NSModul
 static void client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName, address, module);
-       ImageLoader* image;
+               dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName, address, module);
+       const ImageLoader* image;
        const ImageLoader::Symbol* sym;
        if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
                if ( address != NULL)
-                       *address = (void*)image->getExportedSymbolAddress(sym);
+                       *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
                if ( module != NULL)
                        *module = ImageLoaderToNSModule(image);
        }
@@ -327,14 +459,14 @@ static void client_dyld_lookup_and_bind(const char* symbolName, void** address,
 void _dyld_lookup_and_bind_with_hint(const char* symbolName, const char* library_name_hint, void** address, NSModule* module)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\", \"%s\", %p, %p)\n", __func__, symbolName, library_name_hint, address, module);
-       ImageLoader* image;
+               dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__, symbolName, library_name_hint, address, module);
+       const ImageLoader* image;
        const ImageLoader::Symbol* sym;
        // Look for library whose path contains the hint.  If that fails search everywhere
        if (  dyld::flatFindExportedSymbolWithHint(symbolName, library_name_hint, &sym, &image) 
          ||  dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
                if ( address != NULL)
-                       *address = (void*)image->getExportedSymbolAddress(sym);
+                       *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
                if ( module != NULL)
                        *module = ImageLoaderToNSModule(image);
        }
@@ -351,8 +483,8 @@ void _dyld_lookup_and_bind_with_hint(const char* symbolName, const char* library
 NSSymbol NSLookupAndBindSymbol(const char *symbolName)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\")\n", __func__, symbolName);
-       ImageLoader* image;
+               dyld::log("%s(\"%s\")\n", __func__, symbolName);
+       const ImageLoader* image;
        const ImageLoader::Symbol* sym;
        if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
                return SymbolToNSSymbol(sym);
@@ -364,8 +496,8 @@ NSSymbol NSLookupAndBindSymbol(const char *symbolName)
 NSSymbol NSLookupAndBindSymbolWithHint(const char* symbolName, const char* libraryNameHint)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
-       ImageLoader* image;
+               dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
+       const ImageLoader* image;
        const ImageLoader::Symbol* sym;
        bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
        if ( ! found ) {
@@ -377,55 +509,53 @@ NSSymbol NSLookupAndBindSymbolWithHint(const char* symbolName, const char* libra
                
        // return NULL on failure and log
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\", \"%s\") => NULL \n", __func__, symbolName, libraryNameHint);
+               dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__, symbolName, libraryNameHint);
        return NULL;
 }
 
-uint32_t _dyld_image_count(void)
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
-       return dyld::getImageCount();
-}
 
-const struct mach_header* _dyld_get_image_header(uint32_t image_index)
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%u)\n", __func__, image_index);
-       ImageLoader* image = dyld::getIndexedImage(image_index);
-       if ( image != NULL )
-               return (struct mach_header*)image->machHeader();
-       else
-               return NULL;
-}
 
 
 static __attribute__((noinline)) 
 const struct mach_header* addImage(void* callerAddress, const char* path, bool search, bool dontLoad, bool matchInstallName, bool abortOnError)
 {
        ImageLoader*    image = NULL;
+       std::vector<const char*> rpathsFromCallerImage;
        try {
                dyld::clearErrorMessage();
                ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
+               // like dlopen, use rpath from caller image and from main executable
+               if ( callerImage != NULL )
+                       callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
+               ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
+               if ( callerImage != dyld::mainExecutable() ) {
+                       dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
+               }
                dyld::LoadContext context;
                context.useSearchPaths          = search;
+               context.useFallbackPaths        = search;
                context.useLdLibraryPath        = false;
+               context.implicitRPath           = false;
                context.matchByInstallName      = matchInstallName;
                context.dontLoad                        = dontLoad;
                context.mustBeBundle            = false;
                context.mustBeDylib                     = true;
+               context.canBePIE                        = false;
                context.origin                          = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
-               context.rpath                           = NULL; // support not yet implemented
+               context.rpath                           = &callersRPaths;       // rpaths from caller and main executable
                                
                image = load(path, context);
                if ( image != NULL ) {
                        if ( context.matchByInstallName )
                                image->setMatchInstallPath(true);
-                       dyld::link(image, ImageLoader::kNonLazyOnly, ImageLoader::kRunInitializers);
-                       return image->machHeader();
+                       dyld::link(image, false, false, callersRPaths);
+                       dyld::runInitializers(image);
+                       // images added with NSAddImage() can never be unloaded
+                       image->setNeverUnload(); 
                }
        }
        catch (const char* msg) {
+               dyld::garbageCollectImages();
                if ( abortOnError) {
                        char pathMsg[strlen(msg)+strlen(path)+4];
                        strcpy(pathMsg, msg);
@@ -435,18 +565,29 @@ const struct mach_header* addImage(void* callerAddress, const char* path, bool s
                }
                // not halting, so set error state for NSLinkEditError to find
                setLastError(NSLinkEditOtherError, 0, path, msg);
+               free((void*)msg);       // our free() will do nothing if msg is a string literal
+               image = NULL;
        }
-       return NULL;
+       // free rpaths (getRPaths() malloc'ed each string)
+       for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
+               const char* str = *it;
+               free((void*)str);
+       }
+       if ( image == NULL )
+               return NULL;
+       else
+               return image->machHeader();
 }
 
+
 const struct mach_header* NSAddImage(const char* path, uint32_t options)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\", 0x%08X)\n", __func__, path, options);
+               dyld::log("%s(\"%s\", 0x%08X)\n", __func__, path, options);
        const bool dontLoad = ( (options & NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED) != 0 );
        const bool search = ( (options & NSADDIMAGE_OPTION_WITH_SEARCHING) != 0 );
        const bool matchInstallName = ( (options & NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME) != 0 );
-       const bool abortOnError = ( (options & NSADDIMAGE_OPTION_RETURN_ON_ERROR) == 0 );
+       const bool abortOnError = ( (options & (NSADDIMAGE_OPTION_RETURN_ON_ERROR|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED)) == 0 );
        void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
        return addImage(callerAddress, path, search, dontLoad, matchInstallName, abortOnError);
 }
@@ -454,7 +595,7 @@ const struct mach_header* NSAddImage(const char* path, uint32_t options)
 bool NSAddLibrary(const char* path)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\")\n", __func__, path);
+               dyld::log("%s(\"%s\")\n", __func__, path);
        void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
        return (addImage(callerAddress, path, false, false, false, false) != NULL);
 }
@@ -462,7 +603,7 @@ bool NSAddLibrary(const char* path)
 bool NSAddLibraryWithSearching(const char* path)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\")\n", __func__, path);
+               dyld::log("%s(\"%s\")\n", __func__, path);
        void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
        return (addImage(callerAddress, path, true, false, false, false) != NULL);
 }
@@ -476,29 +617,30 @@ bool NSAddLibraryWithSearching(const char* path)
 bool NSIsSymbolNameDefinedInImage(const struct mach_header* mh, const char* symbolName)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, \"%s\")\n", __func__, (void *)mh, symbolName);
+               dyld::log("%s(%p, \"%s\")\n", __func__, (void *)mh, symbolName);
        ImageLoader* image = dyld::findImageByMachHeader(mh);
        if ( image != NULL ) {
-               if ( image->findExportedSymbol(symbolName, NULL, true, NULL) != NULL)
+               if ( image->findExportedSymbol(symbolName, true, NULL) != NULL)
                        return true;
        }
        return false;
 }
 
+
 NSSymbol NSLookupSymbolInImage(const struct mach_header* mh, const char* symbolName, uint32_t options)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, \"%s\", 0x%08X)\n", __func__, mh, symbolName, options);
+               dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, mh, symbolName, options);
        const ImageLoader::Symbol* symbol = NULL;
        dyld::clearErrorMessage();
        ImageLoader* image = dyld::findImageByMachHeader(mh);
        if ( image != NULL ) {
                try {
                        if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY ) {
-                               dyld::link(image, ImageLoader::kLazyOnly, ImageLoader::kDontRunInitializers);
+                               image->bindAllLazyPointers(dyld::gLinkContext, true);
                        }
                        else if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW ) {
-                               dyld::link(image, ImageLoader::kLazyOnlyNoDependents, ImageLoader::kDontRunInitializers);
+                               image->bindAllLazyPointers(dyld::gLinkContext, false);
                        }
                }
                catch (const char* msg) {
@@ -506,10 +648,10 @@ NSSymbol NSLookupSymbolInImage(const struct mach_header* mh, const char* symbolN
                                dyldAPIhalt(__func__, msg);
                        }
                }
-               symbol = image->findExportedSymbol(symbolName, NULL, true, NULL);
+               symbol = image->findExportedSymbol(symbolName, true, NULL);
        }
        if ( dyld::gLogAPIs && (symbol == NULL) )
-               fprintf(stderr, "%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__, mh, symbolName, options);
+               dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__, mh, symbolName, options);
        return SymbolToNSSymbol(symbol);
 }
 
@@ -519,8 +661,8 @@ NSSymbol NSLookupSymbolInImage(const struct mach_header* mh, const char* symbolN
 static bool client_NSIsSymbolNameDefined(const char* symbolName)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "NSIsSymbolNameDefined(\"%s\")\n", symbolName);
-       ImageLoader* image;
+               dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName);
+       const ImageLoader* image;
        const ImageLoader::Symbol* sym;
        return dyld::flatFindExportedSymbol(symbolName, &sym, &image);
 }
@@ -528,8 +670,8 @@ static bool client_NSIsSymbolNameDefined(const char* symbolName)
 bool NSIsSymbolNameDefinedWithHint(const char* symbolName, const char* libraryNameHint)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
-       ImageLoader* image;
+               dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
+       const ImageLoader* image;
        const ImageLoader::Symbol* sym;
        bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
        if ( ! found ) {
@@ -537,16 +679,16 @@ bool NSIsSymbolNameDefinedWithHint(const char* symbolName, const char* libraryNa
                 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
        }
        if ( !found && dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\", \"%s\") => false \n", __func__, symbolName, libraryNameHint);
+               dyld::log("%s(\"%s\", \"%s\") => false \n", __func__, symbolName, libraryNameHint);
        return found;
 }
 
 const char* NSNameOfSymbol(NSSymbol symbol)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, (void *)symbol);
+               dyld::log("%s(%p)\n", __func__, (void *)symbol);
        const char* result = NULL;
-       ImageLoader* image = dyld::findImageContainingAddress(symbol);
+       ImageLoader* image = dyld::findImageContainingSymbol(symbol);
        if ( image != NULL ) 
                result = image->getExportedSymbolName(NSSymbolToSymbol(symbol));
        return result;
@@ -555,61 +697,41 @@ const char* NSNameOfSymbol(NSSymbol symbol)
 void* NSAddressOfSymbol(NSSymbol symbol)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, (void *)symbol);
+               dyld::log("%s(%p)\n", __func__, (void *)symbol);
+       if ( symbol == NULL )
+               return NULL;
        void* result = NULL;
-       ImageLoader* image = dyld::findImageContainingAddress(symbol);
+       ImageLoader* image = dyld::findImageContainingSymbol(symbol);
        if ( image != NULL ) 
-               result = (void*)image->getExportedSymbolAddress(NSSymbolToSymbol(symbol));
+               result = (void*)image->getExportedSymbolAddress(NSSymbolToSymbol(symbol), dyld::gLinkContext);
        return result;
 }
 
 NSModule NSModuleForSymbol(NSSymbol symbol)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, (void *)symbol);
+               dyld::log("%s(%p)\n", __func__, (void *)symbol);
        NSModule result = NULL;
-       ImageLoader* image = dyld::findImageContainingAddress(symbol);
+       ImageLoader* image = dyld::findImageContainingSymbol(symbol);
        if ( image != NULL ) 
                result = ImageLoaderToNSModule(image);
        return result;
 }
 
 
-intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index)
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%u)\n", __func__, image_index);
-       ImageLoader* image = dyld::getIndexedImage(image_index);
-       if ( image != NULL )
-               return image->getSlide();
-       else
-               return 0;
-}
-
-const char* _dyld_get_image_name(uint32_t image_index)
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%u)\n", __func__, image_index);
-       ImageLoader* image = dyld::getIndexedImage(image_index);
-       if ( image != NULL )
-               return image->getLogicalPath();
-       else
-               return NULL;
-}
-
 
 
 bool _dyld_all_twolevel_modules_prebound(void)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
-       return FALSE; // fixme
+               dyld::log("%s()\n", __func__);
+       return FALSE; 
 }
 
 void _dyld_bind_objc_module(const void *objc_module)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, objc_module);
+               dyld::log("%s(%p)\n", __func__, objc_module);
        // do nothing, with new dyld everything already bound
 }
 
@@ -617,12 +739,12 @@ void _dyld_bind_objc_module(const void *objc_module)
 bool _dyld_bind_fully_image_containing_address(const void* address)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, address);
+               dyld::log("%s(%p)\n", __func__, address);
        dyld::clearErrorMessage();
        ImageLoader* image = dyld::findImageContainingAddress(address);
        if ( image != NULL ) {
                try {
-                       dyld::link(image, ImageLoader::kLazyAndNonLazy, ImageLoader::kDontRunInitializers);
+                       image->bindAllLazyPointers(dyld::gLinkContext, true);
                        return true;
                }
                catch (const char* msg) {
@@ -635,7 +757,7 @@ bool _dyld_bind_fully_image_containing_address(const void* address)
 bool _dyld_image_containing_address(const void* address)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, address);
+               dyld::log("%s(%p)\n", __func__, address);
        ImageLoader *imageLoader = dyld::findImageContainingAddress(address);
        return (NULL != imageLoader);
 }
@@ -653,18 +775,21 @@ static NSObjectFileImage createObjectImageFile(ImageLoader* image, const void* a
 NSObjectFileImageReturnCode NSCreateObjectFileImageFromFile(const char* pathName, NSObjectFileImage *objectFileImage)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(\"%s\", ...)\n", __func__, pathName);
+               dyld::log("%s(\"%s\", ...)\n", __func__, pathName);
        try {
                void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
                ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
 
                dyld::LoadContext context;
                context.useSearchPaths          = false;
+               context.useFallbackPaths        = false;
                context.useLdLibraryPath        = false;
+               context.implicitRPath           = false;
                context.matchByInstallName      = false;
                context.dontLoad                        = false;
                context.mustBeBundle            = true;
                context.mustBeDylib                     = false;
+               context.canBePIE                        = false;
                context.origin                          = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
                context.rpath                           = NULL; // support not yet implemented
 
@@ -680,7 +805,9 @@ NSObjectFileImageReturnCode NSCreateObjectFileImageFromFile(const char* pathName
                }
        }
        catch (const char* msg) {
-               //fprintf(stderr, "dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
+               //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
+               dyld::garbageCollectImages();
+               free((void*)msg);
                return NSObjectFileImageInappropriateFile;
        }
        return NSObjectFileImageFailure;
@@ -690,13 +817,13 @@ NSObjectFileImageReturnCode NSCreateObjectFileImageFromFile(const char* pathName
 NSObjectFileImageReturnCode NSCreateObjectFileImageFromMemory(const void* address, size_t size, NSObjectFileImage *objectFileImage)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, %lu, %p)\n", __func__, address, size, objectFileImage);
+               dyld::log("%s(%p, %lu, %p)\n", __func__, address, size, objectFileImage);
        
        try {
                ImageLoader* image = dyld::loadFromMemory((const uint8_t*)address, size, NULL); 
                if ( ! image->isBundle() ) {
                        // this API can only be used with bundles...
-                       delete image; 
+                       dyld::garbageCollectImages();
                        return NSObjectFileImageInappropriateFile;
                }
                // Note:  We DO NOT link the image!  NSLinkModule will do that
@@ -706,7 +833,9 @@ NSObjectFileImageReturnCode NSCreateObjectFileImageFromMemory(const void* addres
                }
        }
        catch (const char* msg) {
-               fprintf(stderr, "dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
+               free((void*)msg);
+               dyld::garbageCollectImages();
+               //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
        }
        return NSObjectFileImageFailure;
 }
@@ -724,14 +853,19 @@ static bool validOFI(NSObjectFileImage objectFileImage)
 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, objectFileImage);
+               dyld::log("%s(%p)\n", __func__, objectFileImage);
        
        if ( validOFI(objectFileImage) ) {
-               // if the image has never been linked or has been unlinked, the image is not in the list of valid images
-               // and we should delete it
-               bool linkedImage = dyld::validImage(objectFileImage->image);
-               if ( ! linkedImage ) 
-                       delete objectFileImage->image;
+               // a failure during NSLinkModule will delete the image
+               if ( objectFileImage->image != NULL ) {
+                       // if the image has never been linked or has been unlinked, the image is not in the list of valid images
+                       // and we should delete it
+                       bool linkedImage = dyld::validImage(objectFileImage->image);
+                       if ( ! linkedImage )  {
+                               ImageLoader::deleteImage(objectFileImage->image);
+                               objectFileImage->image = NULL;
+                       }
+               }
                
                // remove from list of ofi's
                for (std::vector<NSObjectFileImage>::iterator it=sObjectFileImages.begin(); it != sObjectFileImages.end(); it++) {
@@ -744,7 +878,16 @@ bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage)
                // if object was created from a memory, release that memory
                // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
                if ( objectFileImage->imageBaseAddress != NULL ) {
-                       vm_deallocate(mach_task_self(), (vm_address_t)objectFileImage->imageBaseAddress, objectFileImage->imageLength);
+                       bool freed = false;
+                       if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 6) ) {
+                               size_t sz = (*dyld::gLibSystemHelpers->malloc_size)(objectFileImage->imageBaseAddress);
+                               if ( sz != 0 ) {
+                                       (*dyld::gLibSystemHelpers->free)((void*)(objectFileImage->imageBaseAddress));
+                                       freed = true;
+                               }
+                       }
+                       if ( ! freed )
+                               vm_deallocate(mach_task_self(), (vm_address_t)objectFileImage->imageBaseAddress, objectFileImage->imageLength);
                }
                
                // free ofi object
@@ -758,21 +901,21 @@ bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage)
 bool NSHasModInitObjectFileImage(NSObjectFileImage objectFileImage)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, objectFileImage);
+               dyld::log("%s(%p)\n", __func__, objectFileImage);
        return objectFileImage->image->needsInitialization();
 }
 
 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, objectFileImage);
+               dyld::log("%s(%p)\n", __func__, objectFileImage);
        return objectFileImage->image->getExportedSymbolCount();
 }
 
 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p,%d)\n", __func__, objectFileImage, ordinal);
+               dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
        const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedExportedSymbol(ordinal);
        return objectFileImage->image->getExportedSymbolName(sym);      
 }
@@ -780,7 +923,7 @@ const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFile
 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, objectFileImage);
+               dyld::log("%s(%p)\n", __func__, objectFileImage);
        return objectFileImage->image->getImportedSymbolCount();
 }
 
@@ -788,10 +931,10 @@ const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFile
                                                                                                        bool* tentative_definition)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p,%d)\n", __func__, objectFileImage, ordinal);
+               dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
        const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedImportedSymbol(ordinal);
        if ( tentative_definition != NULL ) {
-               ImageLoader::ReferenceFlags flags = objectFileImage->image->geImportedSymbolInfo(sym);
+               ImageLoader::ReferenceFlags flags = objectFileImage->image->getImportedSymbolInfo(sym);
                if ( (flags & ImageLoader::kTentativeDefinition) != 0 )
                        *tentative_definition = true;
                else
@@ -804,7 +947,7 @@ void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage,
                                                                                const char* segmentName, const char* sectionName, unsigned long* size)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p,%s, %s)\n", __func__, objectFileImage, segmentName, sectionName);
+               dyld::log("%s(%p,%s, %s)\n", __func__, objectFileImage, segmentName, sectionName);
 
        void* start;
        size_t length;
@@ -821,127 +964,100 @@ void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage,
 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage, const char* symbolName)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p,%s)\n", __func__, objectFileImage, symbolName);
-       const ImageLoader::Symbol* sym = objectFileImage->image->findExportedSymbol(symbolName, NULL, true, NULL);
+               dyld::log("%s(%p,%s)\n", __func__, objectFileImage, symbolName);
+       const ImageLoader::Symbol* sym = objectFileImage->image->findExportedSymbol(symbolName, true, NULL);
        return ( sym != NULL );
 }
 
-/*
- * Given an imageOffset into an ObjectFileImage, returns 
- * the segment/section name and offset into that section of
- * that imageOffset.  Returns FALSE if the imageOffset is not 
- * in any section.  You can used the resulting sectionOffset to
- * index into the data returned by NSGetSectionDataInObjectFileImage.
- * 
- * First appeared in Mac OS X 10.3 
- *
- * SPI: currently only used by ZeroLink to detect +load methods
- */
-bool 
-NSFindSectionAndOffsetInObjectFileImage(NSObjectFileImage objectFileImage, 
-                                                                               unsigned long imageOffset,
-                                                                               const char** segmentName,       /* can be NULL */
-                                                                               const char** sectionName,       /* can be NULL */
-                                                                               unsigned long* sectionOffset)   /* can be NULL */
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, objectFileImage);
-       
-       return objectFileImage->image->findSection((char*)(objectFileImage->image->getBaseAddress())+imageOffset, segmentName, sectionName, sectionOffset);
-}
-
 
 
 NSModule NSLinkModule(NSObjectFileImage objectFileImage, const char* moduleName, uint32_t options)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, \"%s\", 0x%08X)\n", __func__, objectFileImage, moduleName, options); 
+               dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, objectFileImage, moduleName, options); 
        
        dyld::clearErrorMessage();
        try {
+               if ( (options & NSLINKMODULE_OPTION_CAN_UNLOAD) != 0 )
+                       objectFileImage->image->setCanUnload();
+
                // NSLinkModule allows a bundle to be link multpile times
                // each link causes the bundle to be copied to a new address
                if ( objectFileImage->image->isLinked() ) {
                        // already linked, so clone a new one and link it
-#if 0
-                       fprintf(stderr, "dyld: warning: %s(0x%08X, \"%s\", 0x%08X) called more than once for 0x%08X\n",
-                                       __func__, objectFileImage, moduleName, options, objectFileImage); 
-#endif
                        objectFileImage->image = dyld::cloneImage(objectFileImage->image);
                }
                
-               // if this ofi was made with NSCreateObjectFileImageFromFile() then physical path is already set
-               // if this ofi was create with NSCreateObjectFileImageFromMemory() then the phyiscal path should be set if supplied 
-               if ( (options & NSLINKMODULE_OPTION_TRAILING_PHYS_NAME) != 0 ) {
-                       if ( objectFileImage->imageBaseAddress != NULL ) {
-                               const char* physEnd = &moduleName[strlen(moduleName)+1];
-                               objectFileImage->image->setPath(physEnd);
-                       }
+               // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
+               if ( objectFileImage->image->getPath() == NULL ) {
+                       objectFileImage->image->setPath(moduleName);
+                       // <rdar://problem/8812589> dyld has NULL paths in image info array
+                       dyld_image_info info;
+                       info.imageLoadAddress = objectFileImage->image->machHeader();
+                       info.imageFilePath = moduleName;
+                       info.imageFileModDate = 0;
+                       addImagesToAllImages(1, &info);
                }
-       
-               // set moduleName as the name anyone calling _dyld_get_image_name() will see
-               objectFileImage->image->setLogicalPath(moduleName);
 
                // support private bundles
                if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
                        objectFileImage->image->setHideExports();
        
                // set up linking options
-               ImageLoader::BindingLaziness bindness = ImageLoader::kNonLazyOnly;
-               if ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 )
-                       bindness = ImageLoader::kLazyAndNonLazy;
-               ImageLoader::InitializerRunning runInitializers = ImageLoader::kRunInitializers;
-               if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) != 0 )
-                       runInitializers = ImageLoader::kDontRunInitializersButTellObjc;
+               bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
                
                // load libraries, rebase, bind, to make this image usable
-               dyld::link(objectFileImage->image, bindness, runInitializers);
+               dyld::link(objectFileImage->image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL));
                
+               // bump reference count to keep this bundle from being garbage collected
+               objectFileImage->image->incrementDlopenReferenceCount();
+
+               // run initializers unless magic flag says not to
+               if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
+                       dyld::runInitializers(objectFileImage->image);
+
                return ImageLoaderToNSModule(objectFileImage->image);
        }
        catch (const char* msg) {
+               dyld::garbageCollectImages();
                if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
                        dyldAPIhalt(__func__, msg);
                // not halting, so set error state for NSLinkEditError to find
-               dyld::removeImage(objectFileImage->image);
                setLastError(NSLinkEditOtherError, 0, moduleName, msg);
+               // dyld::link() deleted the image so lose our reference
+               objectFileImage->image = NULL;
+               free((void*)msg);
                return NULL;
        }
 }
 
+
 #if OLD_LIBSYSTEM_SUPPORT
 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr,  moduleName, options); // note name/args translation
+               dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr,  moduleName, options); // note name/args translation
        ImageLoader* image = NULL;
        dyld::clearErrorMessage();
        try {
-               const char* imageName = moduleName;
-               if ( (options & NSLINKMODULE_OPTION_TRAILING_PHYS_NAME) != 0 )
-                       imageName = &moduleName[strlen(moduleName)+1];
-                       
+               const char* imageName = moduleName;                     
                image = dyld::loadFromMemory((const uint8_t*)object_addr, object_size, imageName); 
                
-               if ( (options & NSLINKMODULE_OPTION_TRAILING_PHYS_NAME) != 0 )
-                       image->setLogicalPath(moduleName);
-                       
                if ( image != NULL ) {          
                        // support private bundles
                        if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
                                image->setHideExports();
                
                        // set up linking options
-                       ImageLoader::BindingLaziness bindness = ImageLoader::kNonLazyOnly;
-                       if ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 )
-                               bindness = ImageLoader::kLazyAndNonLazy;
-                       ImageLoader::InitializerRunning runInitializers = ImageLoader::kRunInitializers;
-                       if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) != 0 )
-                               runInitializers = ImageLoader::kDontRunInitializersButTellObjc;
+                       bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
                        
                        // load libraries, rebase, bind, to make this image usable
-                       dyld::link(image, bindness, runInitializers);
+                       dyld::link(image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL));
+                       
+                       // run initializers unless magic flag says not to
+                       if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
+                               dyld::runInitializers(image);
                }
        }
        catch (const char* msg) {
@@ -952,9 +1068,10 @@ static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_s
                // if image was created for this bundle, destroy it
                if ( image != NULL ) {
                        dyld::removeImage(image);
-                       delete image;
+                       ImageLoader::deleteImage(image);
                }
                image = NULL;
+               free((void*)msg);
        }
        return ImageLoaderToNSModule(image);
 }
@@ -963,17 +1080,17 @@ static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_s
 NSSymbol NSLookupSymbolInModule(NSModule module, const char* symbolName)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, \"%s\")\n", __func__, (void *)module, symbolName);
+               dyld::log("%s(%p, \"%s\")\n", __func__, (void *)module, symbolName);
        ImageLoader* image = NSModuleToImageLoader(module);
        if ( image == NULL ) 
                return NULL;
-       return SymbolToNSSymbol(image->findExportedSymbol(symbolName, NULL, false, NULL));
+       return SymbolToNSSymbol(image->findExportedSymbol(symbolName, false, NULL));
 }
 
 const char* NSNameOfModule(NSModule module)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, module);
+               dyld::log("%s(%p)\n", __func__, module);
        ImageLoader* image = NSModuleToImageLoader(module);
        if ( image == NULL ) 
                return NULL;
@@ -983,7 +1100,7 @@ const char* NSNameOfModule(NSModule module)
 const char* NSLibraryNameForModule(NSModule module)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, module);
+               dyld::log("%s(%p)\n", __func__, module);
        ImageLoader* image = NSModuleToImageLoader(module);
        if ( image == NULL ) 
                return NULL;
@@ -993,12 +1110,25 @@ const char* NSLibraryNameForModule(NSModule module)
 bool NSUnLinkModule(NSModule module, uint32_t options)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, 0x%08X)\n", __func__, module, options); 
+               dyld::log("%s(%p, 0x%08X)\n", __func__, module, options); 
        if ( module == NULL )
                return false;
        ImageLoader* image = NSModuleToImageLoader(module);
        if ( image == NULL ) 
                return false;
+       dyld::runImageStaticTerminators(image);
+       if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 13) ) {
+               __cxa_range_t ranges[image->segmentCount()];
+               int rangeCount = 0;
+               for (unsigned int j=0; j < image->segmentCount(); ++j) {
+                       if ( !image->segExecutable(j) )
+                               continue;
+                       ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
+                       ranges[rangeCount].length = image->segSize(j);
+                       ++rangeCount;
+               }
+               (*dyld::gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
+       }
        dyld::removeImage(image);
        
        if ( (options & NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED) != 0 )
@@ -1016,7 +1146,7 @@ bool NSUnLinkModule(NSModule module, uint32_t options)
                        found = true;
        }
        if ( !found )
-               delete image;
+               ImageLoader::deleteImage(image);
        
        return true;
 }
@@ -1025,53 +1155,14 @@ bool NSUnLinkModule(NSModule module, uint32_t options)
 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "NSLinkEditErrorHandlers()\n");
+               dyld::log("NSLinkEditErrorHandlers()\n");
 
        dyld::registerUndefinedHandler((dyld::UndefinedHandler)undefined);
        // no support for multiple or linkedit handlers
 }
 
-const struct mach_header * _dyld_get_image_header_containing_address(const void* address)
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, address);
-       ImageLoader* image = dyld::findImageContainingAddress(address);
-       if ( image != NULL ) 
-               return image->machHeader();
-       return NULL;
-}
 
 
-void _dyld_register_func_for_add_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, (void *)func);
-       dyld::registerAddCallback(func);
-}
-
-void _dyld_register_func_for_remove_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, (void *)func);
-       dyld::registerRemoveCallback(func);
-}
-
-// called by atexit() function installed by crt
-static void _dyld_mod_term_funcs()
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
-       dyld::runTerminators();
-}
-
-// called by crt before main
-static void _dyld_make_delayed_module_initializer_calls()
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
-       dyld::initializeMainExecutable();
-}
-
 
 void NSLinkEditError(NSLinkEditErrors* c, int* errorNumber, const char** fileName, const char** errorString)
 {
@@ -1082,33 +1173,24 @@ void NSLinkEditError(NSLinkEditErrors* c, int* errorNumber, const char** fileNam
        *errorString = dyld::getErrorMessage();
 }
 
+
+
 static void _dyld_register_binding_handler(void * (*bindingHandler)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
+               dyld::log("%s()\n", __func__);
        dyld::gLinkContext.bindingHandler = bindingHandler;
        dyld::gLinkContext.bindingOptions = bindingOptions;
 }
 
-// Call by fork() in libSystem before the kernel trap is done
-static void _dyld_fork_prepare()
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
-}
+#endif //DEPRECATED_APIS_SUPPORTED
 
-// Call by fork() in libSystem after the kernel trap is done on the parent side
-static void _dyld_fork_parent()
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
-}
 
 // Call by fork() in libSystem after the kernel trap is done on the child side
-static void _dyld_fork_child()
+void _dyld_fork_child()
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
+               dyld::log("%s()\n", __func__);
        // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
        // in libSystem for the child of a fork.  But dyld is built with a static copy
        // of libc.a and has its own copy of mach_task_self_ which we reset here.
@@ -1118,44 +1200,22 @@ static void _dyld_fork_child()
        //
        extern mach_port_t      mach_task_self_;
        mach_task_self_ = task_self_trap();
+       
+       // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
+       // page is not copied on fork. <rdar://problem/6797342>
+       // NULL the CoreSymbolication shared memory pointer to prevent a crash.
+       dyld::gProcessInfo->coreSymbolicationShmPage = NULL;
+       // for safety, make sure child starts with clean systemOrderFlag
+       dyld::gProcessInfo->systemOrderFlag = 0;
 }
 
-// Call by fork() in libSystem after the kernel trap is done on the child side after
-// other libSystem child side fixups are done
-static void _dyld_fork_child_final()
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
-}
-
-
-typedef void (*MonitorProc)(char *lowpc, char *highpc);
-
-static void monInitCallback(ImageLoader* image, void* userData)
-{
-       MonitorProc proc = (MonitorProc)userData;
-       void* start;
-       size_t length;
-       if ( image->getSectionContent("__TEXT", "__text", &start, &length) ) {
-               proc((char*)start, (char*)start+length);
-       }
-}
-
-//
-// _dyld_moninit is called from profiling runtime routine moninit().
-// dyld calls back with the range of each __TEXT/__text section in every
-// linked image.
-//
-void _dyld_moninit(MonitorProc proc)
-{
-       dyld::forEachImageDo(&monInitCallback, (void*)proc);
-}
 
+#if DEPRECATED_APIS_SUPPORTED
 // returns true if prebinding was used in main executable
 bool _dyld_launched_prebound()
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
+               dyld::log("%s()\n", __func__);
                
        // Â¥Â¥Â¥ÃŠif we deprecate prebinding, we may want to consider always returning true or false here
        return dyld::mainExecutablePrebound();
@@ -1181,15 +1241,15 @@ static bool NSMakePrivateModulePublic(NSModule module)
        return false;
 }
 
+#endif // DEPRECATED_APIS_SUPPORTED
 
-
-bool lookupDyldFunction(const char* name, uintptr_t* address)
+int _dyld_func_lookup(const char* name, void** address)
 {
        for (const dyld_func* p = dyld_funcs; p->name != NULL; ++p) {
            if ( strcmp(p->name, name) == 0 ) {
                        if( p->implementation == unimplemented )
-                               fprintf(stderr, "unimplemented dyld function: %s\n", p->name);
-                       *address = (uintptr_t)p->implementation;
+                               dyld::log("unimplemented dyld function: %s\n", p->name);
+                       *address = p->implementation;
                        return true;
            }
        }
@@ -1198,79 +1258,233 @@ bool lookupDyldFunction(const char* name, uintptr_t* address)
 }
 
 
-static void registerThreadHelpers(const dyld::ThreadingHelpers* helpers)
+static void registerThreadHelpers(const dyld::LibSystemHelpers* helpers)
 {
-       // We need to make sure libSystem's lazy pointer's are bound
-       // before installing thred helpers.
-       // The reason for this is that if accessing the lock requires
-       // a lazy pointer to be bound (and it does when multi-module
-       // libSystem) is not prebound, the lazy handler will be
-       // invoked which tries to acquire the lock again...an infinite 
-       // loop.
-       ImageLoader* image = dyld::findImageContainingAddress(helpers);
-       dyld::link(image, ImageLoader::kLazyOnly, ImageLoader::kDontRunInitializers);
-
-       dyld::gThreadHelpers = helpers;
+       dyld::gLibSystemHelpers = helpers;
+       
+       // let gdb know it is safe to run code in inferior that might call malloc()
+       dyld::gProcessInfo->libSystemInitialized = true;        
+       
+#if !SUPPORT_ZERO_COST_EXCEPTIONS
+       if ( helpers->version >= 5 )  {
+               // create key use by dyld exception handling
+               pthread_key_t key;
+               int result = helpers->pthread_key_create(&key, NULL);
+               if ( result == 0 )
+                       __Unwind_SjLj_SetThreadKey(key);
+       }
+#endif
 }
 
 
 static void dlerrorClear()
 {
-       if ( dyld::gThreadHelpers != NULL ) {
-               char* buffer = (*dyld::gThreadHelpers->getThreadBufferFor_dlerror)(1);
+       if ( dyld::gLibSystemHelpers != NULL ) {
+               // <rdar://problem/10595338> dlerror buffer leak
+               // dlerrorClear() should not force allocation, but zero it if already allocated
+               if ( dyld::gLibSystemHelpers->version >= 10 ) {
+                       if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
+                               return;
+               }
+
+               // first char of buffer is flag whether string (starting at second char) is valid
+               char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
                buffer[0] = '\0';
+               buffer[1] = '\0';
        }
 }
 
 static void dlerrorSet(const char* msg)
 {
-       if ( dyld::gThreadHelpers != NULL ) {
-               char* buffer = (*dyld::gThreadHelpers->getThreadBufferFor_dlerror)(strlen(msg)+1);
-               strcpy(buffer, msg);
+       if ( dyld::gLibSystemHelpers != NULL ) {
+               // first char of buffer is flag whether string (starting at second char) is valid
+               char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(strlen(msg)+2);
+               buffer[0] = '\1';
+               strcpy(&buffer[1], msg);
        }
 }
 
 
+bool dlopen_preflight(const char* path)
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%s)\n", __func__, path);
+
+       dlerrorClear();
+       
+#if DYLD_SHARED_CACHE_SUPPORT
+       // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
+       // if requested path is to something in the dyld shared cache, always succeed
+       if ( dyld::inSharedCache(path) )
+               return true;
+#endif
+       
+       CRSetCrashLogMessage("dyld: in dlopen_preflight()");
+       
+       bool result = false;
+       std::vector<const char*> rpathsFromCallerImage;
+       try {
+               void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
+               ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
+               // for dlopen, use rpath from caller image and from main executable
+               if ( callerImage != NULL )
+                       callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
+               ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
+               if ( callerImage != dyld::mainExecutable() ) {
+                       dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
+               }
+
+               ImageLoader*    image = NULL;
+               const bool leafName = (strchr(path, '/') == NULL);
+               const bool absolutePath = (path[0] == '/');
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+               char canonicalPath[PATH_MAX]; 
+               // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
+               if ( !leafName ) {
+                       // make path canonical if it contains a // or ./
+                       if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
+                               const char* lastSlash = strrchr(path, '/');
+                               char dirPath[PATH_MAX]; 
+                               if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
+                                       dirPath[lastSlash-path] = '\0';
+                                       if ( realpath(dirPath, canonicalPath) ) {
+                                               strlcat(canonicalPath, "/", sizeof(canonicalPath));
+                                               if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
+                                                       // if all fit in buffer, use new canonical path
+                                                       path = canonicalPath;
+                                               }
+                                       }
+                               }
+                       }
+               }
+#endif
+               dyld::LoadContext context;
+               context.useSearchPaths  = true;
+               context.useFallbackPaths= leafName;                                     // a partial path implies don't use fallback paths
+               context.useLdLibraryPath= leafName;                                     // a leafname implies should search 
+               context.implicitRPath   = !absolutePath;                        // a non-absolute path implies try rpath searching 
+               context.matchByInstallName = true;
+               context.dontLoad                = false;
+               context.mustBeBundle    = false;
+               context.mustBeDylib             = false;
+               context.canBePIE                = true;
+               context.origin                  = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
+               context.rpath                   = &callersRPaths;       // rpaths from caller and main executable
+               
+               image = load(path, context);
+               if ( image != NULL ) {
+                       dyld::preflight(image, callersRPaths);  // image object deleted by dyld::preflight()
+                       result = true;
+               }
+       }
+       catch (const char* msg) {
+               const char* str = dyld::mkstringf("dlopen_preflight(%s): %s", path, msg);
+               dlerrorSet(str);
+               free((void*)str);
+               free((void*)msg);       // our free() will do nothing if msg is a string literal
+       }
+       // free rpaths (getRPaths() malloc'ed each string)
+       for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
+               const char* str = *it;
+               free((void*)str);
+       }
+       CRSetCrashLogMessage(NULL);
+       return result;
+}
+
 
 void* dlopen(const char* path, int mode)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%s, 0x%08X)\n", __func__, path, mode);
+               dyld::log("%s(%s, 0x%08X)\n", __func__, ((path==NULL) ? "NULL" : path), mode);
 
        dlerrorClear();
        
        // passing NULL for path means return magic object
        if ( path == NULL ) {
-               return RTLD_DEFAULT;
+               // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
+               if ( (mode & RTLD_FIRST) != 0 )
+                       return RTLD_MAIN_ONLY;
+               else
+                       return RTLD_DEFAULT;
        }
        
+       // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
+       bool lockHeld = false;
+       if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 4) ) {
+               dyld::gLibSystemHelpers->acquireGlobalDyldLock();
+               CRSetCrashLogMessage("dyld: in dlopen()");
+               lockHeld = true;
+       }
+               
+       void* result = NULL;
+       ImageLoader* image = NULL;
+       std::vector<const char*> rpathsFromCallerImage;
+       ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
        try {
                void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
                ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
-
-               ImageLoader*    image = NULL;
+               if ( (mode & RTLD_NOLOAD) == 0 ) {
+                       // for dlopen, use rpath from caller image and from main executable
+                       if ( callerImage != NULL )
+                               callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
+                       if ( callerImage != dyld::mainExecutable() )
+                               dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
+               }
+               const bool leafName = (strchr(path, '/') == NULL);
+               const bool absolutePath = (path[0] == '/');
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+               char canonicalPath[PATH_MAX]; 
+               // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
+               if ( !leafName ) {
+                       // make path canonical if it contains a // or ./
+                       if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
+                               const char* lastSlash = strrchr(path, '/');
+                               char dirPath[PATH_MAX]; 
+                               if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
+                                       dirPath[lastSlash-path] = '\0';
+                                       if ( realpath(dirPath, canonicalPath) ) {
+                                               strlcat(canonicalPath, "/", sizeof(canonicalPath));
+                                               if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
+                                                       // if all fit in buffer, use new canonical path
+                                                       path = canonicalPath;
+                                               }
+                                       }
+                               }
+                       }
+               }
+#endif
                dyld::LoadContext context;
                context.useSearchPaths  = true;
-               context.useLdLibraryPath= (strchr(path, '/') == NULL);  // a leafname implies should search 
+               context.useFallbackPaths= leafName;                             // a partial path means no fallback paths
+               context.useLdLibraryPath= leafName;                             // a leafname implies should search 
+               context.implicitRPath   = !absolutePath;                // a non-absolute path implies try rpath searching 
                context.matchByInstallName = true;
-               context.dontLoad = ( (mode & RTLD_NOLOAD) != 0 );
+               context.dontLoad                = ( (mode & RTLD_NOLOAD) != 0 );
                context.mustBeBundle    = false;
                context.mustBeDylib             = false;
+               context.canBePIE                = true;
                context.origin                  = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
-               context.rpath                   = NULL; // support not yet implemented
+               context.rpath                   = &callersRPaths;                               // rpaths from caller and main executable
                
                image = load(path, context);
                if ( image != NULL ) {
-                       image->incrementReferenceCount();
-                       if ( ! image->isLinked() ) {
-                               ImageLoader::BindingLaziness bindiness = ImageLoader::kNonLazyOnly;
-                               if ( (mode & RTLD_NOW) != 0 )
-                                       bindiness = ImageLoader::kLazyAndNonLazy;
-                               dyld::link(image, bindiness, ImageLoader::kRunInitializers);
-                               // only hide exports if image is not already in use
-                               if ( (mode & RTLD_LOCAL) != 0 )
-                                       image->setHideExports(true);
+                       // bump reference count.  Do this before link() so that if an initializer calls dlopen and fails
+                       // this image is not garbage collected
+                       image->incrementDlopenReferenceCount();
+                       // link in all dependents
+                       if ( (mode & RTLD_NOLOAD) == 0 ) {
+                               bool alreadyLinked = image->isLinked();
+                               bool forceLazysBound = ( (mode & RTLD_NOW) != 0 );
+                               dyld::link(image, forceLazysBound, false, callersRPaths);
+                               if ( ! alreadyLinked ) {
+                                       // only hide exports if image is not already in use
+                                       if ( (mode & RTLD_LOCAL) != 0 )
+                                               image->setHideExports(true);
+                               }
                        }
+                       
                        // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
                        // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated. 
                        // The subtle differences are: 
@@ -1278,34 +1492,92 @@ void* dlopen(const char* path, int mode)
                        //  2) If someone does a supsequent dlopen() on the same image, whether the same address should be used. 
                        if ( (mode & RTLD_NODELETE) != 0 )
                                image->setLeaveMapped();
-                       return image;
+                       
+                       // release global dyld lock early, this enables initializers to do threaded operations
+                       if ( lockHeld ) {
+                               CRSetCrashLogMessage(NULL);
+                               dyld::gLibSystemHelpers->releaseGlobalDyldLock();
+                               lockHeld = false;
+                       }
+                       
+                       // RTLD_NOLOAD means dlopen should fail unless path is already loaded. 
+                       // don't run initializers when RTLD_NOLOAD is set.  This only matters if dlopen() is
+                       // called from within an initializer because it can cause initializers to run
+                       // out of order. Most uses of RTLD_NOLOAD are "probes".  If they want initialzers
+                       // to run, then don't use RTLD_NOLOAD.
+                       if ( (mode & RTLD_NOLOAD) == 0 ) {
+                               // run initializers
+                               dyld::runInitializers(image);
+                       }
+                       
+                       // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
+                       // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
+                       if ( (mode & RTLD_FIRST) != 0 )
+                               result = (void*)(((uintptr_t)image)|1);
+                       else
+                               result = image;
                }
        }
        catch (const char* msg) {
-               const char* format = "dlopen(%s, %d): %s";
-               char temp[strlen(format)+strlen(path)+strlen(msg)+10];
-               sprintf(temp, format, path, mode, msg);
-               dlerrorSet(temp);
+               if ( image != NULL ) {
+                       // load() succeeded but, link() failed
+                       // back down reference count and do GC
+                       image->decrementDlopenReferenceCount();
+                       if ( image->dlopenCount() == 0 )
+                               dyld::garbageCollectImages();
+               }
+               const char* str = dyld::mkstringf("dlopen(%s, %d): %s", path, mode, msg);
+               if ( dyld::gLogAPIs )
+                       dyld::log("  %s() failed, error: '%s'\n", __func__, str);
+               dlerrorSet(str);
+               free((void*)str);
+               free((void*)msg);       // our free() will do nothing if msg is a string literal
+               result = NULL;
        }
-       return NULL;
+       // free rpaths (getRPaths() malloc'ed each string)
+       for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
+               const char* str = *it;
+               free((void*)str);
+       }
+       
+       // when context.dontLoad is set, load() returns NULL instead of throwing an exception 
+       if ( (mode & RTLD_NOLOAD) && (result == NULL) ) {
+               dlerrorSet("image not already loaded");
+       }
+       
+       if ( lockHeld ) {
+               CRSetCrashLogMessage(NULL);
+               dyld::gLibSystemHelpers->releaseGlobalDyldLock();
+       }
+       if ( dyld::gLogAPIs && (result != NULL) )
+               dyld::log("  %s(%s) ==> %p\n", __func__, path, result);
+       return result;
 }
 
+
+
 int dlclose(void* handle)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p)\n", __func__, handle);
+               dyld::log("%s(%p)\n", __func__, handle);
 
-       ImageLoader* image = (ImageLoader*)handle;
+       // silently accept magic handles for main executable
+       if ( handle == RTLD_MAIN_ONLY )
+               return 0;
+       if ( handle == RTLD_DEFAULT )
+               return 0;
+       
+       ImageLoader* image = (ImageLoader*)(((uintptr_t)handle) & (-4));        // clear mode bits
        if ( dyld::validImage(image) ) {
-               if ( image->decrementReferenceCount() ) {
-                       // for now, only bundles can be unloaded
-                       // to unload dylibs we would need to track all direct and indirect uses
-                       if ( image->isBundle() ) {
-                               dyld::removeImage(image);
-                               delete image;
-                       }
-               }
                dlerrorClear();
+               // decrement use count
+               if ( image->decrementDlopenReferenceCount() ) {
+                       dlerrorSet("dlclose() called too many times");
+                       return -1;
+               }
+               // remove image if reference count went to zero
+               if ( image->dlopenCount() == 0 )
+                       dyld::garbageCollectImages();
                return 0;
        }
        else {
@@ -1319,34 +1591,42 @@ int dlclose(void* handle)
 int dladdr(const void* address, Dl_info* info)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, %p)\n", __func__, address, info);
+               dyld::log("%s(%p, %p)\n", __func__, address, info);
 
+       CRSetCrashLogMessage("dyld: in dladdr()");
        ImageLoader* image = dyld::findImageContainingAddress(address);
        if ( image != NULL ) {
-               info->dli_fname = image->getLogicalPath();
-               info->dli_fbase = (void*)image->machHeader();   
-               // find closest exported symbol in the image
-               const uint32_t exportCount = image->getExportedSymbolCount();
-               const ImageLoader::Symbol* bestSym = NULL;
-               const void* bestAddr = 0;
-               for(uint32_t i=0; i < exportCount; ++i) {
-                       const ImageLoader::Symbol* sym = image->getIndexedExportedSymbol(i);
-                       const void* symAddr = (void*)image->getExportedSymbolAddress(sym);
-                       if ( (symAddr <= address) && (bestAddr < symAddr) ) {
-                               bestSym = sym;
-                               bestAddr = symAddr;
-                       }
-               }
-               if ( bestSym != NULL ) {
-                       info->dli_sname = image->getExportedSymbolName(bestSym) + 1; // strip off leading underscore
-                       info->dli_saddr = (void*)bestAddr;
+               info->dli_fname = image->getRealPath();
+               info->dli_fbase = (void*)image->machHeader();
+               if ( address == info->dli_fbase ) {
+                       // special case lookup of header
+                       info->dli_sname = "__dso_handle";
+                       info->dli_saddr = info->dli_fbase;
+                       CRSetCrashLogMessage(NULL);
+                       return 1; // success
                }
-               else {
+               // find closest symbol in the image
+               info->dli_sname = image->findClosestSymbol(address, (const void**)&info->dli_saddr);
+               // never return the mach_header symbol
+               if ( info->dli_saddr == info->dli_fbase ) {
                        info->dli_sname = NULL;
                        info->dli_saddr = NULL;
+                       CRSetCrashLogMessage(NULL);
+                       return 1; // success
                }
+               if ( info->dli_sname != NULL ) {
+                       if ( info->dli_sname[0] == '_' )
+                               info->dli_sname = info->dli_sname +1; // strip off leading underscore
+                       //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
+                       CRSetCrashLogMessage(NULL);
+                       return 1; // success
+               }
+               info->dli_sname = NULL;
+               info->dli_saddr = NULL;
+               CRSetCrashLogMessage(NULL);
                return 1; // success
        }
+       CRSetCrashLogMessage(NULL);
        return 0;  // failure
 }
 
@@ -1354,13 +1634,21 @@ int dladdr(const void* address, Dl_info* info)
 char* dlerror()
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
+               dyld::log("%s()\n", __func__);
+
+       if ( dyld::gLibSystemHelpers != NULL ) {
+               // if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
+               if ( dyld::gLibSystemHelpers->version >= 10 ) {
+                       if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
+                               return NULL;
+               }
 
-       if ( dyld::gThreadHelpers != NULL ) {
-               char* buffer = (*dyld::gThreadHelpers->getThreadBufferFor_dlerror)(1);
-               // if no error set, return NULL
-               if ( buffer[0] != '\0' )
-                       return buffer;
+               // first char of buffer is flag whether string (starting at second char) is valid
+               char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
+               if ( buffer[0] != '\0' ) {      // if valid buffer
+                       buffer[0] = '\0';               // mark invalid, so next call to dlerror returns NULL
+                       return &buffer[1];              // return message
+               }
        }
        return NULL;
 }
@@ -1368,11 +1656,12 @@ char* dlerror()
 void* dlsym(void* handle, const char* symbolName)
 {
        if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s(%p, %s)\n", __func__, handle, symbolName);
+               dyld::log("%s(%p, %s)\n", __func__, handle, symbolName);
 
+       CRSetCrashLogMessage("dyld: in dlsym()");
        dlerrorClear();
 
-       ImageLoader* image;
+       const ImageLoader* image;
        const ImageLoader::Symbol* sym;
 
        // dlsym() assumes symbolName passed in is same as in C source code
@@ -1384,12 +1673,28 @@ void* dlsym(void* handle, const char* symbolName)
        // magic "search all" handle
        if ( handle == RTLD_DEFAULT ) {
                if ( dyld::flatFindExportedSymbol(underscoredName, &sym, &image) ) {
-                       return (void*)image->getExportedSymbolAddress(sym);
+                       CRSetCrashLogMessage(NULL);
+                       return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
                }
-               const char* format = "dlsym(RTLD_DEFAULT, %s): symbol not found";
-               char temp[strlen(format)+strlen(symbolName)+2];
-               sprintf(temp, format, symbolName);
-               dlerrorSet(temp);
+               const char* str = dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName);
+               dlerrorSet(str);
+               free((void*)str);
+               CRSetCrashLogMessage(NULL);
+               return NULL;
+       }
+       
+       // magic "search only main executable" handle
+       if ( handle == RTLD_MAIN_ONLY ) {
+               image = dyld::mainExecutable();
+               sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
+               if ( sym != NULL ) {
+                       CRSetCrashLogMessage(NULL);
+                       return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
+               }
+               const char* str = dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName);
+               dlerrorSet(str);
+               free((void*)str);
+               CRSetCrashLogMessage(NULL);
                return NULL;
        }
        
@@ -1397,248 +1702,149 @@ void* dlsym(void* handle, const char* symbolName)
        if ( handle == RTLD_NEXT ) {
                void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
                ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
-               sym = callerImage->findExportedSymbolInDependentImages(underscoredName, &image); // don't search image, but do search what it links against
+               sym = callerImage->findExportedSymbolInDependentImages(underscoredName, dyld::gLinkContext, &image); // don't search image, but do search what it links against
                if ( sym != NULL ) {
-                       return (void*)image->getExportedSymbolAddress(sym);
+                       CRSetCrashLogMessage(NULL);
+                       return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
                }
-               const char* format = "dlsym(RTLD_NEXT, %s): symbol not found";
-               char temp[strlen(format)+strlen(symbolName)+2];
-               sprintf(temp, format, symbolName);
-               dlerrorSet(temp);
+               const char* str = dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName);
+               dlerrorSet(str);
+               free((void*)str);
+               CRSetCrashLogMessage(NULL);
                return NULL;
        }
-#ifdef RTLD_SELF
        // magic "search me, then what I would see" handle
        if ( handle == RTLD_SELF ) {
                void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
                ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
-               sym = callerImage->findExportedSymbolInImageOrDependentImages(underscoredName, &image); // search image and what it links against
+               sym = callerImage->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
                if ( sym != NULL ) {
-                       return (void*)image->getExportedSymbolAddress(sym);
+                       CRSetCrashLogMessage(NULL);
+                       return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
                }
-               const char* format = "dlsym(RTLD_SELF, %s): symbol not found";
-               char temp[strlen(format)+strlen(symbolName)+2];
-               sprintf(temp, format, symbolName);
-               dlerrorSet(temp);
+               const char* str = dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName);
+               dlerrorSet(str);
+               free((void*)str);
+               CRSetCrashLogMessage(NULL);
                return NULL;
        }
-#endif
        // real handle
-       image = (ImageLoader*)handle;
+       image = (ImageLoader*)(((uintptr_t)handle) & (-4));     // clear mode bits
        if ( dyld::validImage(image) ) {
-               sym = image->findExportedSymbolInImageOrDependentImages(underscoredName, &image); // search image and what it links against
+               if ( (((uintptr_t)handle) & 1) != 0 )
+                       sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
+               else
+                       sym = image->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
+               
                if ( sym != NULL ) {
-                       return (void*)image->getExportedSymbolAddress(sym);
+                       CRSetCrashLogMessage(NULL);
+                       ImageLoader* callerImage = NULL;
+                       if ( sDynamicInterposing ) {
+                               // only take time to look up caller, if dynamic interposing in use
+                               void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
+                               callerImage = dyld::findImageContainingAddress(callerAddress);
+                       }
+                       return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage);
                }
-               const char* format = "dlsym(%p, %s): symbol not found";
-               char temp[strlen(format)+strlen(symbolName)+20];
-               sprintf(temp, format, handle, symbolName);
-               dlerrorSet(temp);
+               const char* str = dyld::mkstringf("dlsym(%p, %s): symbol not found", handle, symbolName);
+               dlerrorSet(str);
+               free((void*)str);
        }
        else {
                dlerrorSet("invalid handle passed to dlsym()");
        }
+       CRSetCrashLogMessage(NULL);
        return NULL;
 }
 
 
-static void commitRepreboundFiles(std::vector<ImageLoader*> files, bool unmapOld)
-{
-       // tell file system to flush all dirty buffers to disk
-       // after this sync, the _redoprebinding files will be on disk
-       sync();
 
-       // now commit (swap file) for each re-prebound image
-       // this only updates directories, since the files have already been flushed by previous sync()
-       for (std::vector<ImageLoader*>::iterator it=files.begin(); it != files.end(); it++) {
-               (*it)->reprebindCommit(dyld::gLinkContext, true, unmapOld);
-       }
 
-       // tell file system to flush all dirty buffers to disk
-       // this should flush out all directory changes caused by the file swapping
-       sync();
-}
 
 
-#define UPDATE_PREBINDING_DRY_RUN  0x00000001
-#define UPDATE_PREBINDING_PROGRESS 0x00000002
 
-//
-// SPI called only by update_prebinding tool to redo prebinding in all prebound files specified
-// There must be no dylibs loaded when this fnction is called.
-//
-__attribute__((noreturn))
-static void _dyld_update_prebinding(int pathCount, const char* paths[], uint32_t flags)
-{
-       if ( dyld::gLogAPIs )
-               fprintf(stderr, "%s()\n", __func__);
 
-       // list of requested dylibs actually loaded
-       std::vector<ImageLoader*> preboundImages;
-       
-       try {
-               // verify no dylibs loaded
-               if ( dyld::getImageCount() != 1 )
-                       throw "_dyld_update_prebinding cannot be called with dylib already loaded";
-                       
-               const uint32_t max_allowed_link_errors = 10;
-               uint32_t link_error_count = 0;
-               
-               // load and link each dylib
-               for (int i=0; i < pathCount; ++i) {
-                       dyld::LoadContext context;
-                       context.useSearchPaths          = false;
-                       context.matchByInstallName      = true;
-                       context.dontLoad                        = false;
-                       context.mustBeBundle            = false;
-                       context.mustBeDylib                     = true;
-                       context.origin                          = NULL;         // @loader_path not allowed in prebinding list
-                       context.rpath                           = NULL;         // support not yet implemented
-                       
-                       ImageLoader* image = NULL;
-                       try {
-                               image = dyld::load(paths[i], context);
-                               // bind lazy and non-lazy symbols, but don't run initializers
-                               // this may bring in other dylibs later in the list or missing from list, but that is ok
-                               dyld::link(image, ImageLoader::kLazyAndNonLazy, ImageLoader::kDontRunInitializers);
-                               // recored images we successfully loaded
-                               preboundImages.push_back(image);
-                       }
-                       catch (const char* msg) {
-                               if ( dyld::gLinkContext.verbosePrebinding || (UPDATE_PREBINDING_DRY_RUN & flags) ) {
-                                       const char *stage;
-                                       if ( image == NULL ) // load exception
-                                               stage = "load";
-                                       else // link exception
-                                               stage = "link";
-                                       fprintf(stderr, "update_prebinding: warning: could not %s %s: %s\n", stage, paths[i], msg);
-                               }
-                               if ( image != NULL )
-                                       link_error_count++;
-                               if ( link_error_count > max_allowed_link_errors )
-                                       throw;
-                       }
-               }
-               
-               // find missing images
-               uint32_t loadedImageCount =     dyld::getImageCount();
-               if ( loadedImageCount > (preboundImages.size()+1) ) {
-                       if ( dyld::gLinkContext.verbosePrebinding || (UPDATE_PREBINDING_DRY_RUN & flags) )
-                               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");
-                       for (uint32_t i=1; i < loadedImageCount; ++i) {
-                               ImageLoader* target = dyld::getIndexedImage(i);
-                               bool found = false;
-                               for (std::vector<ImageLoader*>::iterator it=preboundImages.begin(); it != preboundImages.end(); it++) {
-                                       if ( *it == target ) {
-                                               found = true;
-                                               break;
-                                       }
-                               }
-                               if ( !found ) 
-                                       if ( dyld::gLinkContext.verbosePrebinding || (UPDATE_PREBINDING_DRY_RUN & flags) )
-                                               fprintf(stderr, "  %s\n", target->getPath());
-                       }
-               }
 
-               // warn about unprebound files in the list
-               bool unpreboundWarned = false;
-               for (std::vector<ImageLoader*>::iterator it=preboundImages.begin(); it != preboundImages.end(); it++) {
-                       if ( ! (*it)->isPrebindable() && (*it != dyld::mainExecutable()) ) {
-                               if ( ! unpreboundWarned ) {
-                                       if ( dyld::gLinkContext.verbosePrebinding || (UPDATE_PREBINDING_DRY_RUN & flags) )
-                                               fprintf(stderr, "update_prebinding: warning: the following dylibs were specified but were not built prebound\n");
-                                       unpreboundWarned = true;
-                               }
-                               if ( dyld::gLinkContext.verbosePrebinding || (UPDATE_PREBINDING_DRY_RUN & flags) )
-                                       fprintf(stderr, "  %s\n", (*it)->getPath());
-                       }
-               }
-               
-               if(UPDATE_PREBINDING_DRY_RUN & flags) {
-                       fprintf(stderr, "update_prebinding: dry-run: no changes were made to the filesystem.\n");
-               }
-               else {
-                       uint32_t imageCount = preboundImages.size();
-                       uint32_t imageNumber = 1;
-
-                       // on Intel system, update_prebinding is run twice: i386, then emulated ppc
-                       // calculate fudge factors so that progress output represents both runs
-                       int denomFactor = 1;
-                       int numerAddend = 0;
-                       if (UPDATE_PREBINDING_PROGRESS & flags) {
-               #if __i386__
-                               // i386 half runs first, just double denominator
-                               denomFactor = 2;
-               #endif  
-               #if __ppc__
-                               // if emulated ppc, double denominator and shift numerator
-                               int mib[] = { CTL_KERN, KERN_CLASSIC, getpid() };
-                               int is_emulated = 0;
-                               size_t len = sizeof(int);
-                               int ret = sysctl(mib, 3, &is_emulated, &len, NULL, 0);
-                               if ((ret != -1) && is_emulated) {
-                                       denomFactor = 2;
-                                       numerAddend = imageCount;
-                               }
-               #endif
-                       }
 
-                       // tell each image to write itself out re-prebound
-                       struct timeval currentTime = { 0 , 0 };
-                       gettimeofday(&currentTime, NULL);
-                       time_t timestamp = currentTime.tv_sec;
-                       std::vector<ImageLoader*> updatedImages;
-                       for (std::vector<ImageLoader*>::iterator it=preboundImages.begin(); it != preboundImages.end(); it++) {
-                               uint64_t freespace = (*it)->reprebind(dyld::gLinkContext, timestamp);
-                               updatedImages.push_back(*it);
-                               if(UPDATE_PREBINDING_PROGRESS & flags) {
-                                       fprintf(stdout, "update_prebinding: progress: %3u/%u\n", imageNumber+numerAddend, imageCount*denomFactor);
-                                       fflush(stdout);
-                                       imageNumber++;
-                               }
-                               // see if we are running low on disk space (less than 32MB is "low")
-                               const uint64_t kMinFreeSpace = 32*1024*1024;  
-                               if ( freespace < kMinFreeSpace ) {
-                                       if ( dyld::gLinkContext.verbosePrebinding || (UPDATE_PREBINDING_DRY_RUN & flags) )
-                                               fprintf(stderr, "update_prebinding: disk space down to %lluMB, committing %lu prebound files\n", freespace/(1024*1024), updatedImages.size());
-                                       // commit files processed so far, to free up more disk space
-                                       commitRepreboundFiles(updatedImages, true);
-                                       // empty list of temp files
-                                       updatedImages.clear();
-                               }
-                       }
-               
-                       // commit them, don't need to unmap old, cause we are done
-                       commitRepreboundFiles(updatedImages, false);
-               }
-       }
-       catch (const char* msg) {
-               // delete temp files
-               try {
-                       for (std::vector<ImageLoader*>::iterator it=preboundImages.begin(); it != preboundImages.end(); it++) {
-                               (*it)->reprebindCommit(dyld::gLinkContext, false, false);
-                       }
-               }
-               catch (const char* commitMsg) {
-                       fprintf(stderr, "update_prebinding: error: %s\n", commitMsg);
-               }
-               fprintf(stderr, "update_prebinding: error: %s\n", msg);
-               exit(1);
+const struct dyld_all_image_infos* _dyld_get_all_image_infos()
+{
+       return dyld::gProcessInfo;
+}
+
+#if SUPPORT_ZERO_COST_EXCEPTIONS
+static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info)
+{
+       //if ( dyld::gLogAPIs )
+       //      dyld::log("%s(%p, %p)\n", __func__, addr, info);
+       
+       ImageLoader* image = dyld::findImageContainingAddress(addr);
+       if ( image != NULL ) {
+               image->getUnwindInfo(info);
+               return true;
        }
-       exit(0);
+       return false;
 }
+#endif
 
 
+void dyld_register_image_state_change_handler(dyld_image_states state, bool batch, 
+                                                                                       dyld_image_state_change_handler handler)
+{
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%d, %d, %p)\n", __func__, state, batch, handler);
+       if ( batch )
+               dyld::registerImageStateBatchChangeHandler(state, handler);
+       else
+               dyld::registerImageStateSingleChangeHandler(state, handler);
+}
 
-static const struct dyld_all_image_infos* _dyld_get_all_image_infos()
+const char* dyld_image_path_containing_address(const void* address)
 {
-       return &dyld_all_image_infos;
+       if ( dyld::gLogAPIs )
+               dyld::log("%s(%p)\n", __func__, address);
+
+       ImageLoader* image = dyld::findImageContainingAddress(address);
+       if ( image != NULL )
+               return image->getRealPath();
+       return NULL;
 }
 
 
 
+bool dyld_shared_cache_some_image_overridden()
+{
+ #if DYLD_SHARED_CACHE_SUPPORT
+       return dyld::gSharedCacheOverridden;
+ #else
+    return true;
+ #endif
+}
 
 
+void dyld_dynamic_interpose(const struct mach_header* mh, const struct dyld_interpose_tuple array[], size_t count)
+{
+       if ( mh == NULL )
+               return;
+       if ( array == NULL )
+               return;
+       if ( count == 0 )
+               return;
+       ImageLoader* image = dyld::findImageByMachHeader(mh);
+       if ( image == NULL )
+               return;
+       
+       // make pass at bound references in this image and update them
+       dyld::gLinkContext.dynamicInterposeArray = array;
+       dyld::gLinkContext.dynamicInterposeCount = count;
+               image->dynamicInterpose(dyld::gLinkContext);
+       dyld::gLinkContext.dynamicInterposeArray = NULL;
+       dyld::gLinkContext.dynamicInterposeCount = 0;
+       
+       // leave interposing info so any future (lazy) binding will get it too
+       image->addDynamicInterposingTuples(array, count);
+       
+       sDynamicInterposing = true;
+}