Esempio n. 1
0
static void* AppleGLGetProcAddress (const GLubyte *name)
{
  static const struct mach_header* image = NULL;
  NSSymbol symbol;
  char* symbolName;
  if (NULL == image)
  {
    image = NSAddImage("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", NSADDIMAGE_OPTION_RETURN_ON_ERROR);
  }
  /* prepend a '_' for the Unix C symbol mangling convention */
  symbolName = malloc(strlen((const char*)name) + 2);
  strcpy(symbolName+1, (const char*)name);
  symbolName[0] = '_';
  symbol = NULL;
  /* if (NSIsSymbolNameDefined(symbolName))
	 symbol = NSLookupAndBindSymbol(symbolName); */
  symbol = image ? NSLookupSymbolInImage(image, symbolName, NSLOOKUPSYMBOLINIMAGE_OPTION_BIND | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR) : NULL;
  free(symbolName);
  return symbol ? NSAddressOfSymbol(symbol) : NULL;
}
Esempio n. 2
0
static void * _module_getsymbol( module_handle_t handle,
                                 const char * psz_function )
{
#if defined(HAVE_DL_DYLD)
    NSSymbol sym = NSLookupSymbolInModule( handle, psz_function );
    return NSAddressOfSymbol( sym );

#elif defined(HAVE_DL_BEOS)
    void * p_symbol;
    if( B_OK == get_image_symbol( handle, psz_function,
                                  B_SYMBOL_TYPE_TEXT, &p_symbol ) )
    {
        return p_symbol;
    }
    else
    {
        return NULL;
    }

#elif defined(HAVE_DL_WINDOWS) && defined(UNDER_CE)
    wchar_t psz_real[256];
    MultiByteToWideChar( CP_ACP, 0, psz_function, -1, psz_real, 256 );

    return (void *)GetProcAddress( handle, psz_real );

#elif defined(HAVE_DL_WINDOWS) && defined(WIN32)
    return (void *)GetProcAddress( handle, (char *)psz_function );

#elif defined(HAVE_DL_DLOPEN)
    return dlsym( handle, psz_function );

#elif defined(HAVE_DL_SHL_LOAD)
    void *p_sym;
    shl_findsym( &handle, psz_function, TYPE_UNDEFINED, &p_sym );
    return p_sym;

#endif
}
Esempio n. 3
0
static void*
LookupSymbol(const mach_header* aLib, const char* aSymbolName)
{
    // Try to use |NSLookupSymbolInImage| since it is faster than searching
    // the global symbol table.  If we couldn't get a mach_header pointer
    // for the XPCOM dylib, then use |NSLookupAndBindSymbol| to search the
    // global symbol table (this shouldn't normally happen, unless the user
    // has called XPCOMGlueStartup(".") and relies on libxpcom.dylib
    // already being loaded).
    NSSymbol sym = nsnull;
    if (aLib) {
        sym = NSLookupSymbolInImage(aLib, aSymbolName,
                                 NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                 NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
    } else {
        if (NSIsSymbolNameDefined(aSymbolName))
            sym = NSLookupAndBindSymbol(aSymbolName);
    }
    if (!sym)
        return nsnull;

    return NSAddressOfSymbol(sym);
}
Esempio n. 4
0
Togl_FuncPtr
Togl_GetProcAddr(const char *funcname)
{
#if defined(TOGL_OSMESA)
    return (Togl_FuncPtr) OSMesaGetProcAddress(funcname);
#elif defined(TOGL_WGL)
    return (Togl_FuncPtr) wglGetProcAddress(funcname);
#elif defined(__APPLE__)
    char    buf[256];

    snprintf(buf, sizeof buf - 1, "_%s", funcname);
    buf[sizeof buf - 1] = '\0';
    if (NSIsSymbolNameDefined(buf)) {
        NSSymbol nssym;

        nssym = NSLookupAndBindSymbol(buf);
        if (nssym)
            return (Togl_FuncPtr) NSAddressOfSymbol(nssym);
    }
    return NULL;
#else
#  if defined(TOGL_X11) && defined(GLX_VERSION_1_4)
    /* Strictly speaking, we can only call glXGetProcAddress if glXQueryVersion 
     * says we're using version 1.4 or later. */
    return (Togl_FuncPtr) glXGetProcAddress(funcname);
#  else
    /* Linux, IRIX, OSF/1, ? */
    static void *dlHandle = NULL;

    if (dlHandle == NULL)
        dlHandle = dlopen(NULL, RTLD_LAZY);
    /* Strictly speaking, the following cast of a data pointer to a function
     * pointer is not legal in ISO C, but we don't have any choice. */
    return (Togl_FuncPtr) dlsym(dlHandle, funcname);
#  endif
#endif
}
static void *_CFBundleDYLDGetSymbolByNameWithSearch(CFBundleRef bundle, CFStringRef symbolName, Boolean globalSearch) {
    void *result = NULL;
    char buff[1026];
    NSSymbol symbol = NULL;
    
    buff[0] = '_';
    if (CFStringGetCString(symbolName, &(buff[1]), 1024, kCFStringEncodingUTF8)) {
        if (bundle->_moduleCookie) {
            symbol = NSLookupSymbolInModule((NSModule)(bundle->_moduleCookie), buff);
        } else if (bundle->_imageCookie) {
            symbol = NSLookupSymbolInImage(bundle->_imageCookie, buff, NSLOOKUPSYMBOLINIMAGE_OPTION_BIND|NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
        } 
        if (!symbol && !bundle->_moduleCookie && (!bundle->_imageCookie || globalSearch)) {
            char hintBuff[1026];
            CFStringRef executableName = _CFBundleCopyExecutableName(bundle, NULL, NULL);
            hintBuff[0] = '\0';
            if (executableName) {
                if (!CFStringGetCString(executableName, hintBuff, 1024, kCFStringEncodingUTF8)) hintBuff[0] = '\0';
                CFRelease(executableName);
            }
            // Nowdays, NSIsSymbolNameDefinedWithHint() and NSLookupAndBindSymbolWithHint()
            // are identical, except the first just returns a bool, so checking with the
            // Is function first just causes a redundant lookup.
            // This returns NULL on failure.
            symbol = NSLookupAndBindSymbolWithHint(buff, hintBuff);
        }
        if (symbol) result = NSAddressOfSymbol(symbol);
#if defined(DEBUG)
        if (!result) CFLog(__kCFLogBundle, CFSTR("dyld cannot find symbol %@ in %@"), symbolName, bundle);
#endif /* DEBUG */
#if LOG_BUNDLE_LOAD
        printf("bundle %p handle %p module %p image %p dyld returns symbol %p for %s\n", bundle, bundle->_handleCookie, bundle->_moduleCookie, bundle->_imageCookie, result, buff + 1);
#endif /* LOG_BUNDLE_LOAD */
    }
    return result;
}
static void *LinkSymbol(const char *symname, const char *fwhint)
{
	return NSAddressOfSymbol(NSLookupAndBindSymbolWithHint(symname, fwhint));
}
Esempio n. 7
0
static void checkBundle(const char* path, bool unlinkBeforeDestroy)
{
	int fd = open(path, O_RDONLY, 0);
	if ( fd == -1 ) {
		printf("[FAIL] open(%s) failed", path);
		exit(0);
	}

	struct stat stat_buf;
	if ( fstat(fd, &stat_buf) == -1) {
		printf("[FAIL] fstat() failed\n");
		exit(0);
	}

	void* loadAddress = mmap(NULL, stat_buf.st_size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
	if ( loadAddress == ((void*)(-1)) ) {
		printf("[FAIL] mmap() failed\n");
		exit(0);
	}

	close(fd);

	NSObjectFileImage ofi;
	if ( NSCreateObjectFileImageFromMemory(loadAddress, stat_buf.st_size, &ofi) != NSObjectFileImageSuccess ) {
		printf("[FAIL] NSCreateObjectFileImageFromMemory failed\n");
		exit(0);
	}

	NSModule mod = NSLinkModule(ofi, path, NSLINKMODULE_OPTION_NONE);
	if ( mod == NULL ) {
		printf("[FAIL] NSLinkModule failed\n");
		exit(0);
	}
	
   if ( !unlinkBeforeDestroy ) {
        // API lets you destroy ofi and NSModule lives on
        if ( !NSDestroyObjectFileImage(ofi) ) {
            printf("[FAIL] NSDestroyObjectFileImage failed\n");
            exit(0);
        }
    }

	NSSymbol sym = NSLookupSymbolInModule(mod, "_fooInBundle");
	if ( sym == NULL ) {
		printf("[FAIL] NSLookupSymbolInModule failed\n");
		exit(0);
	}

	void* func = NSAddressOfSymbol(sym);
	if ( func == NULL ) {
		printf("[FAIL] NSAddressOfSymbol failed\n");
		exit(0);
	}

    Dl_info info;
    if ( dladdr(func, &info) == 0 ) {
        printf("[FAIL] dladdr(&p, xx) failed\n");
        exit(0);
    }
    //printf("_fooInBundle found in %s\n", info.dli_fname);

    if ( !NSUnLinkModule(mod, NSUNLINKMODULE_OPTION_NONE) ) {
            printf("[FAIL] NSUnLinkModule failed\n");
            exit(0);
    }

    if ( dladdr(func, &info) != 0 ) {
        printf("[FAIL] dladdr(&p, xx) found but should not have\n");
        exit(0);
    }

    if ( unlinkBeforeDestroy ) {
        if ( !NSDestroyObjectFileImage(ofi) ) {
            printf("[FAIL] NSDestroyObjectFileImage failed\n");
            exit(0);
        }
    }
}
Esempio n. 8
0
MODULE_SCOPE Tcl_PackageInitProc *
TclpFindSymbol(
    Tcl_Interp *interp,		/* For error reporting. */
    Tcl_LoadHandle loadHandle,	/* Handle from TclpDlopen. */
    CONST char *symbol)		/* Symbol name to look up. */
{
    Tcl_DyldLoadHandle *dyldLoadHandle = (Tcl_DyldLoadHandle *) loadHandle;
    Tcl_PackageInitProc *proc = NULL;
    const char *errMsg = NULL;
    Tcl_DString ds;
    const char *native;

    native = Tcl_UtfToExternalDString(NULL, symbol, -1, &ds);
#if TCL_DYLD_USE_DLFCN
    if (dyldLoadHandle->dlHandle) {
	proc = dlsym(dyldLoadHandle->dlHandle, native);
	if (proc) {
	    TclLoadDbgMsg("dlsym() successful");
	} else {
	    errMsg = dlerror();
	    TclLoadDbgMsg("dlsym() failed: %s", errMsg);
	}
    } else
#endif /* TCL_DYLD_USE_DLFCN */
    {
#if TCL_DYLD_USE_NSMODULE || defined(TCL_LOAD_FROM_MEMORY)
	NSSymbol nsSymbol = NULL;
	Tcl_DString newName;

	/*
	 * dyld adds an underscore to the beginning of symbol names.
	 */

	Tcl_DStringInit(&newName);
	Tcl_DStringAppend(&newName, "_", 1);
	native = Tcl_DStringAppend(&newName, native, -1);
	if (dyldLoadHandle->dyldLibHeader) {
	    nsSymbol = NSLookupSymbolInImage(dyldLoadHandle->dyldLibHeader,
		    native, NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW |
		    NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
	    if (nsSymbol) {
		TclLoadDbgMsg("NSLookupSymbolInImage() successful");
#ifdef DYLD_SUPPORTS_DYLIB_UNLOADING
		/*
		 * Until dyld supports unloading of MY_DYLIB binaries, the
		 * following is not needed.
		 */

		NSModule module = NSModuleForSymbol(nsSymbol);
		Tcl_DyldModuleHandle *modulePtr = dyldLoadHandle->modulePtr;

		while (modulePtr != NULL) {
		    if (module == modulePtr->module) {
			break;
		    }
		    modulePtr = modulePtr->nextPtr;
		}
		if (modulePtr == NULL) {
		    modulePtr = (Tcl_DyldModuleHandle *)
			    ckalloc(sizeof(Tcl_DyldModuleHandle));
		    modulePtr->module = module;
		    modulePtr->nextPtr = dyldLoadHandle->modulePtr;
		    dyldLoadHandle->modulePtr = modulePtr;
		}
#endif /* DYLD_SUPPORTS_DYLIB_UNLOADING */
	    } else {
		NSLinkEditErrors editError;
		int errorNumber;
		const char *errorName;

		NSLinkEditError(&editError, &errorNumber, &errorName, &errMsg);
		TclLoadDbgMsg("NSLookupSymbolInImage() failed: %s", errMsg);
	    }
	} else if (dyldLoadHandle->modulePtr) {
	    nsSymbol = NSLookupSymbolInModule(
		    dyldLoadHandle->modulePtr->module, native);
	    if (nsSymbol) {
		TclLoadDbgMsg("NSLookupSymbolInModule() successful");
	    } else {
		TclLoadDbgMsg("NSLookupSymbolInModule() failed");
	    }
	}
	if (nsSymbol) {
	    proc = NSAddressOfSymbol(nsSymbol);
	    if (proc) {
		TclLoadDbgMsg("NSAddressOfSymbol() successful");
	    } else {
		TclLoadDbgMsg("NSAddressOfSymbol() failed");
	    }
	}
	Tcl_DStringFree(&newName);
#endif /* TCL_DYLD_USE_NSMODULE */
    }
    Tcl_DStringFree(&ds);
    if (errMsg) {
	Tcl_AppendResult(interp, errMsg, NULL);
    }
    return proc;
}
Esempio n. 9
0
void * Instance_Module_Load(char * name, void ** Load, void ** Unload)
{
   char fileName[MAX_LOCATION];
   char extension[MAX_EXTENSION];
   void * library = null;

   *Load = null;
   *Unload = null;

#if defined(__WIN32__)
   strcpy(fileName, name);
   GetExtension(fileName, extension);
   if(!extension[0])
      strcat(fileName, ".dll");

   {
      uint16 _wfileName[MAX_LOCATION];
      UTF8toUTF16Buffer(fileName, _wfileName, MAX_LOCATION);
      library = LoadLibraryW(_wfileName);
   }
   if(library)
   {
      *Load = (void *)GetProcAddress(library, "__ecereDll_Load@4");
      *Unload = (void *)GetProcAddress(library, "__ecereDll_Unload@4");
      if(!*Load)
         FreeLibrary(library);
   }
#elif defined(__unix__) || defined(__APPLE__)
   strcpy(fileName, "lib");
   strcat(fileName, name);
   GetExtension(fileName, extension);
   if(!extension[0])
#if defined(__APPLE__)
      strcat(fileName, ".dylib");
#else
      strcat(fileName, ".so");
#endif

   library = dlopen(fileName, RTLD_LAZY);
   if(library)
   {
      *Load = dlsym(library, "__ecereDll_Load");
      *Unload = dlsym(library, "__ecereDll_Unload");
      if(!*Load)
         dlclose(library);
   }
#elif defined(__APPLE__)
   strcpy(fileName, "lib");
   strcat(fileName, name);
   GetExtension(fileName, extension);
   if(!extension[0])
      strcat(fileName, ".dylib");
   {
      NSObjectFileImage *fileImage;
      NSObjectFileImageReturnCode returnCode = NSCreateObjectFileImageFromFile(fileName, &fileImage);

      if(returnCode == NSObjectFileImageSuccess)
      {
         printf("NSObjectFileImageSuccess!\n");
         library = NSLinkModule(fileImage,fileName, 
              NSLINKMODULE_OPTION_RETURN_ON_ERROR
            | NSLINKMODULE_OPTION_PRIVATE);
         // NSDestroyObjectFileImage(fileImage);
         if(library)
         {
            *Load = NSAddressOfSymbol(NSLookupSymbolInModule(library, "__ecereDll_Load")); 
            *Unload = NSAddressOfSymbol(NSLookupSymbolInModule(library, "__ecereDll_Unload"));
            if(!*Load)
            {
               NSUnLinkModule(library, 0);
            }
            else
               printf("Found Load!\n");
         }
      }
      else
         printf("No Success :(\n");
   }
#endif
   return library;
}
Esempio n. 10
0
static void *dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetError)
{
	NSSymbol *nssym = 0;
#ifdef __GCC__
	void *caller = __builtin_return_address(1);	/* Be *very* careful about inlining */
#else
        void *caller = NULL;
#endif
	const struct mach_header *caller_mh = 0;
	const char* savedErrorStr = NULL;
	resetdlerror();
#ifndef RTLD_SELF
#define	RTLD_SELF		((void *) -3)
#endif
	if (NULL == dls)
		dls = RTLD_SELF;
	if ((RTLD_NEXT == dls) || (RTLD_SELF == dls))
	{
		if (dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage)
		{
			caller_mh = image_for_address(caller);
			if (RTLD_SELF == dls)
			{
				/* FIXME: We should be using the NSModule api, if SELF is an MH_BUNDLE
				 * But it appears to work anyway, and looking at the code in dyld_libfuncs.c
				 * this is acceptable.
				 */
				if (dyld_NSIsSymbolNameDefinedInImage(caller_mh, symbol))
				{
					nssym = dyld_NSLookupSymbolInImage(caller_mh,
													   symbol,
													   NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
													   NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
				}
			}
			if (!nssym)
			{
				if (RTLD_SELF == dls)
					savedErrorStr = dyld_error_str();
				nssym = search_linked_libs(caller_mh, symbol);
			}
		}
		else
		{
			if (canSetError)
				error("RTLD_SELF and RTLD_NEXT are not supported");
			return NULL;
		}
	}
	if (!nssym)
	{

		if (RTLD_DEFAULT == dls)
		{
			dls = &mainStatus;
		}
		if (!isValidStatus(dls))
			return NULL;

		if (dls->module != MAGIC_DYLIB_MOD)
		{
			nssym = NSLookupSymbolInModule(dls->module, symbol);
			if (!nssym && NSIsSymbolNameDefined(symbol))
			{
				debug("Searching dependencies");
				savedErrorStr = dyld_error_str();
				nssym = search_linked_libs(get_mach_header_from_NSModule(dls->module), symbol);
			}
		}
		else if (dls->lib && dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage)
		{
			if (dyld_NSIsSymbolNameDefinedInImage(dls->lib, symbol))
			{
				nssym = dyld_NSLookupSymbolInImage(dls->lib,
												   symbol,
												   NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
												   NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
			}
			else if (NSIsSymbolNameDefined(symbol))
			{
				debug("Searching dependencies");
				savedErrorStr = dyld_error_str();
				nssym = search_linked_libs(dls->lib, symbol);
			}
		}
		else if (dls->module == MAGIC_DYLIB_MOD)
		{
			/* Global context, use NSLookupAndBindSymbol */
			if (NSIsSymbolNameDefined(symbol))
			{
				/* There doesn't seem to be a return on error option for this call???
				   this is potentially broken, if binding fails, it will improperly
				   exit the application. */
				nssym = NSLookupAndBindSymbol(symbol);
			}
			else
			{
				if (savedErrorStr)
					free((char*)savedErrorStr);			
				savedErrorStr = malloc(256);
				snprintf((char*)savedErrorStr, 256, "Symbol \"%s\" not in global context",symbol);	
			}
		}
	}
	/* Error reporting */
	if (!nssym)
	{
		if (!savedErrorStr || !strlen(savedErrorStr))
		{
			if (savedErrorStr)
				free((char*)savedErrorStr);
			savedErrorStr = malloc(256);
			snprintf((char*)savedErrorStr, 256,"Symbol \"%s\" not found",symbol);
		}
		if (canSetError)
		{
			error(savedErrorStr);
		}
		else
		{
			debug(savedErrorStr);
		}
		if (savedErrorStr)
			free((char*)savedErrorStr);
		return NULL;
	}
	return NSAddressOfSymbol(nssym);
}
Esempio n. 11
0
GdkGLProc
_gdk_x11_gl_get_proc_address (const char *proc_name)
{
#ifdef __APPLE__

#define _GDK_GL_LIBGL_PATH  "/usr/X11R6/lib/libGL.1.dylib"
#define _GDK_GL_LIBGLU_PATH "/usr/X11R6/lib/libGLU.1.dylib"

    typedef GdkGLProc (*__glXGetProcAddressProc) (const GLubyte *);
    static __glXGetProcAddressProc glx_get_proc_address = (__glXGetProcAddressProc) -1;
    const char *image_name;
    static const struct mach_header *libgl_image = NULL;
    static const struct mach_header *libglu_image = NULL;
    NSSymbol symbol;
    char *symbol_name;
    GdkGLProc proc_address;

    GDK_GL_NOTE_FUNC ();

    if (strncmp ("glu", proc_name, 3) != 0)
    {
        /* libGL */

        if (libgl_image == NULL)
        {
            image_name = g_getenv ("GDK_GL_LIBGL_PATH");
            if (image_name == NULL)
                image_name = _GDK_GL_LIBGL_PATH;

            GDK_GL_NOTE (MISC, g_message (" - Add Mach-O image %s", image_name));

            libgl_image = NSAddImage (image_name, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
            if (libgl_image == NULL)
            {
                g_warning ("Cannot add Mach-O image %s", image_name);
                return NULL;
            }
        }

        if (glx_get_proc_address == (__glXGetProcAddressProc) -1)
        {
            /*
             * Look up glXGetProcAddress () function.
             */

            symbol = NSLookupSymbolInImage (libgl_image,
                                            "_glXGetProcAddress",
                                            NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                            NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
            if (symbol == NULL)
            {
                symbol = NSLookupSymbolInImage (libgl_image,
                                                "_glXGetProcAddressARB",
                                                NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                                NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
                if (symbol == NULL)
                {
                    symbol = NSLookupSymbolInImage (libgl_image,
                                                    "_glXGetProcAddressEXT",
                                                    NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                                    NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
                }
            }
            GDK_GL_NOTE (MISC, g_message (" - glXGetProcAddress () - %s",
                                          symbol ? "supported" : "not supported"));
            if (symbol != NULL)
                glx_get_proc_address = NSAddressOfSymbol (symbol);
            else
                glx_get_proc_address = NULL;
        }

        /* Try glXGetProcAddress () */

        if (glx_get_proc_address != NULL)
        {
            proc_address = glx_get_proc_address ((unsigned char *) proc_name);
            GDK_GL_NOTE (IMPL, g_message (" ** glXGetProcAddress () - %s",
                                          proc_address ? "succeeded" : "failed"));
            if (proc_address != NULL)
                return proc_address;
        }

        /* Try Mach-O dyld */

        symbol_name = g_strconcat ("_", proc_name, NULL);

        symbol = NSLookupSymbolInImage (libgl_image,
                                        symbol_name,
                                        NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                        NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
        GDK_GL_NOTE (MISC, g_message (" - NSLookupSymbolInImage () - %s",
                                      symbol ? "succeeded" : "failed"));

        g_free (symbol_name);

        if (symbol != NULL)
            return NSAddressOfSymbol (symbol);
    }
    else
    {
        /* libGLU */

        if (libglu_image == NULL)
        {
            image_name = g_getenv ("GDK_GL_LIBGLU_PATH");
            if (image_name == NULL)
                image_name = _GDK_GL_LIBGLU_PATH;

            GDK_GL_NOTE (MISC, g_message (" - Add Mach-O image %s", image_name));

            libglu_image = NSAddImage (image_name, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
            if (libglu_image == NULL)
            {
                g_warning ("Cannot add Mach-O image %s", image_name);
                return NULL;
            }
        }

        symbol_name = g_strconcat ("_", proc_name, NULL);

        symbol = NSLookupSymbolInImage (libglu_image,
                                        symbol_name,
                                        NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                        NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
        GDK_GL_NOTE (MISC, g_message (" - NSLookupSymbolInImage () - %s",
                                      symbol ? "succeeded" : "failed"));

        g_free (symbol_name);

        if (symbol != NULL)
            return NSAddressOfSymbol (symbol);
    }

    return NULL;

#else  /* __APPLE__ */

    typedef GdkGLProc (*__glXGetProcAddressProc) (const GLubyte *);
    static __glXGetProcAddressProc glx_get_proc_address = (__glXGetProcAddressProc) -1;
    gchar *file_name;
    GModule *module;
    GdkGLProc proc_address = NULL;

    GDK_GL_NOTE_FUNC ();

    if (strncmp ("glu", proc_name, 3) != 0)
    {
        if (glx_get_proc_address == (__glXGetProcAddressProc) -1)
        {
            /*
             * Look up glXGetProcAddress () function.
             */

            file_name = g_module_build_path (NULL, "GL");
            GDK_GL_NOTE (MISC, g_message (" - Open %s", file_name));
            module = g_module_open (file_name, G_MODULE_BIND_LAZY);
            g_free (file_name);

            if (module != NULL)
            {
                g_module_symbol (module, "glXGetProcAddress",
                                 (gpointer) &glx_get_proc_address);
                if (glx_get_proc_address == NULL)
                {
                    g_module_symbol (module, "glXGetProcAddressARB",
                                     (gpointer) &glx_get_proc_address);
                    if (glx_get_proc_address == NULL)
                    {
                        g_module_symbol (module, "glXGetProcAddressEXT",
                                         (gpointer) &glx_get_proc_address);
                    }
                }
                GDK_GL_NOTE (MISC, g_message (" - glXGetProcAddress () - %s",
                                              glx_get_proc_address ? "supported" : "not supported"));
                g_module_close (module);
            }
            else
            {
                g_warning ("Cannot open %s", file_name);
                glx_get_proc_address = NULL;
                return NULL;
            }
        }

        /* Try glXGetProcAddress () */

        if (glx_get_proc_address != NULL)
        {
            proc_address = glx_get_proc_address ((unsigned char *) proc_name);
            GDK_GL_NOTE (IMPL, g_message (" ** glXGetProcAddress () - %s",
                                          proc_address ? "succeeded" : "failed"));
            if (proc_address != NULL)
                return proc_address;
        }

        /* Try g_module_symbol () */

        /* libGL */
        file_name = g_module_build_path (NULL, "GL");
        GDK_GL_NOTE (MISC, g_message (" - Open %s", file_name));
        module = g_module_open (file_name, G_MODULE_BIND_LAZY);
        g_free (file_name);

        if (module != NULL)
        {
            g_module_symbol (module, proc_name, (gpointer) &proc_address);
            GDK_GL_NOTE (MISC, g_message (" - g_module_symbol () - %s",
                                          proc_address ? "succeeded" : "failed"));
            g_module_close (module);
        }
        else
        {
            g_warning ("Cannot open %s", file_name);
        }

        if (proc_address == NULL)
        {
            /* libGLcore */
            file_name = g_module_build_path (NULL, "GLcore");
            GDK_GL_NOTE (MISC, g_message (" - Open %s", file_name));
            module = g_module_open (file_name, G_MODULE_BIND_LAZY);
            g_free (file_name);

            if (module != NULL)
            {
                g_module_symbol (module, proc_name, (gpointer) &proc_address);
                GDK_GL_NOTE (MISC, g_message (" - g_module_symbol () - %s",
                                              proc_address ? "succeeded" : "failed"));
                g_module_close (module);
            }
        }
    }
    else
    {
        /* libGLU */
        file_name = g_module_build_path (NULL, "GLU");
        GDK_GL_NOTE (MISC, g_message (" - Open %s", file_name));
        module = g_module_open (file_name, G_MODULE_BIND_LAZY);
        g_free (file_name);

        if (module != NULL)
        {
            g_module_symbol (module, proc_name, (gpointer) &proc_address);
            GDK_GL_NOTE (MISC, g_message (" - g_module_symbol () - %s",
                                          proc_address ? "succeeded" : "failed"));
            g_module_close (module);
        }
        else
        {
            g_warning ("Cannot open %s", file_name);
        }
    }

    return proc_address;

#endif /* __APPLE__ */
}
Esempio n. 12
0
void *
cc_dl_sym(cc_libhandle handle, const char * symbolname)
{
  void * ptr = NULL;  

#ifdef HAVE_DL_LIB

  if ((handle == NULL) || (handle->nativehnd == NULL)) return NULL;
  ptr = dlsym((void *)handle->nativehnd, symbolname);

  if (cc_dl_debugging()) {
    const char * e = dlerror();
    if (e) {
      cc_debugerror_post("cc_dl_sym", "dlsym(\"%s\", \"%s\") failed with: '%s'",
                         handle->libname.getString(), symbolname, e);
    }
  }

#elif defined (HAVE_DYLD_RUNTIME_BINDING) 

  /* Note: The dlopen() version returns NULL here if handle or
     handle->nativehnd are NULL, but we do not need a handle for
     symbol lookup on Mac OS X - if we have one, it makes the lookup
     faster, but that's all, so we can get away with having no valid
     handle. */

  NSSymbol symbol = NULL;
  char * mangledname;
  NSLinkEditErrors c;
  int e;
  const char * file;
  const char * errstr;

  if (cc_dl_debugging()) {
    cc_debugerror_postinfo("cc_dl_sym", "Looking up symbol %s", 
                       symbolname);
  }

  mangledname = malloc(strlen(symbolname) + 2);
  strcpy(mangledname + 1, symbolname);
  mangledname[0] = '_';

  if (handle && handle->nativehnd) {
    if (NSIsSymbolNameDefinedInImage(handle->nativehnd, mangledname))
      symbol = NSLookupSymbolInImage(handle->nativehnd, mangledname,
               NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
               NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
  } 

  /* If we did not specifically load the library ourselves
     (handle->nativehnd being NULL), or if the symbol could not be
     found in the library, let's try if we can find it in any of the
     loaded libs. */

  if (!symbol && NSIsSymbolNameDefined(mangledname)) {
    symbol = NSLookupAndBindSymbol(mangledname);
  } 

  if (cc_dl_debugging()) {
    if (symbol == NULL) {
      NSLinkEditError(&c, &e, &file, &errstr);
      cc_debugerror_post("cc_dl_sym", "symbol %s not found: %s", 
                         symbolname, errstr);
    }
  }

  free (mangledname);
  ptr = symbol ? NSAddressOfSymbol(symbol) : NULL;  
  
#elif defined (HAVE_WINDLL_RUNTIME_BINDING)

  if ((handle == NULL) || (handle->nativehnd == NULL)) return NULL;
 
  ptr = dl_internal::cstyle_cast<void *>(GetProcAddress((HINSTANCE) handle->nativehnd, symbolname));

  if (cc_dl_debugging() && (ptr == NULL)) {
    cc_string funcstr;
    cc_string_construct(&funcstr);
    cc_string_sprintf(&funcstr, "GetProcAddress(\"%s\", \"%s\")", handle->libname.getString(), symbolname);
    cc_win32_print_error("cc_dl_sym", cc_string_get_text(&funcstr), GetLastError());
    cc_string_clean(&funcstr);
  }

#elif defined (HAVE_DLD_LIB)

  {
    int retval = shl_findsym((shl_t *)(&handle->nativehnd), symbolname, TYPE_UNDEFINED, &ptr);

    if (cc_dl_debugging() && (retval == -1)) {
      const char * e = strerror(errno);
      cc_debugerror_post("cc_dl_sym", "shl_findsym(\"%s\", \"%s\", ...) failed with: '%s'",
                         handle->libname.getString(), symbolname, e);
    }
  }

#endif

  return ptr;
}
Esempio n. 13
0
static void * dlsymIntern(struct dlstatus * dls, const char *symbol,int canSetError)
{
    NSSymbol * nssym = 0;
    /* If it is a module - use NSLookupSymbolInModule */
    if (dls->module != MAGIC_DYLIB_MOD) 
    {
    
        nssym = NSLookupSymbolInModule(dls->module, symbol);
        if (!nssym && canSetError)
            error("unable to find symbol \"%s\"", symbol);
    }        
    else 
    {
        if (dls->lib != NULL) 
        {
            /* dylib, use NSIsSymbolNameDefinedInImage */
            if (NSIsSymbolNameDefinedInImage(dls->lib,symbol)) 
            {
                nssym = NSLookupSymbolInImage(dls->lib,
                                  symbol,
                                  NSLOOKUPSYMBOLINIMAGE_OPTION_BIND 
                                  | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
                                  );
            }
        }
        else 
        {
            /* Global context, use NSLookupAndBindSymbol */
            if (NSIsSymbolNameDefined(symbol)) 
            {
                /* There doesn't seem to be a return on error option for this call???
                   this is potentially broken, if binding fails, it will improperly
                   exit the application. If anyone comes up with an example of this
                   happening I will install error handlers before making this call, and
                   remove them afterwards. The error handlers themselves can cause problems
                   as they are global to the process, and errors that have nothing to do
                   with dlcompat could cause the error handlers to get called */
                nssym = NSLookupAndBindSymbol(symbol);
            }    
        }                          
        if (!nssym) 
        {
            NSLinkEditErrors ler;
            int lerno;
            const char* errstr;
            const char* file;        
            NSLinkEditError(&ler,&lerno,&file,&errstr);    
            if (errstr && strlen(errstr)) 
            {    
                if (canSetError)    
                    error(errstr);
                debug("%s",errstr);    
            }
            else if (canSetError) 
            {
                error("unable to find symbol \"%s\"", symbol);
            }
            
        }
    }
    if (!nssym)
        return NULL;
    return NSAddressOfSymbol(nssym);
}
Esempio n. 14
0
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
					const char *pathname, FILE *fp)
{
	dl_funcptr p = NULL;
	char funcname[258];
	NSObjectFileImageReturnCode rc;
	NSObjectFileImage image;
	NSModule newModule;
	NSSymbol theSym;
	const char *errString;
	char errBuf[512];

	PyOS_snprintf(funcname, sizeof(funcname), "_init%.200s", shortname);

#ifdef USE_DYLD_GLOBAL_NAMESPACE
	if (NSIsSymbolNameDefined(funcname)) {
		theSym = NSLookupAndBindSymbol(funcname);
		p = (dl_funcptr)NSAddressOfSymbol(theSym);
		return p;
	}
#endif
	rc = NSCreateObjectFileImageFromFile(pathname, &image);
	switch(rc) {
		default:
		case NSObjectFileImageFailure:
		case NSObjectFileImageFormat:
			/* for these a message is printed on stderr by dyld */
			errString = "Can't create object file image";
		break;
		case NSObjectFileImageSuccess:
			errString = NULL;
			break;
		case NSObjectFileImageInappropriateFile:
			errString = "Inappropriate file type for dynamic loading";
			break;
		case NSObjectFileImageArch:
			errString = "Wrong CPU type in object file";
			break;
		case NSObjectFileImageAccess:
			errString = "Can't read object file (no access)";
			break;
	}
	if (errString == NULL) {
		newModule = NSLinkModule(image, pathname, LINKOPTIONS);
		if (newModule == NULL) {
			int errNo;
			const char *fileName, *moreErrorStr;
			NSLinkEditErrors c;
			NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr );
			PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s", 
					fileName, moreErrorStr);
			errString = errBuf;
		}
	}
	if (errString != NULL) {
		PyErr_SetString(PyExc_ImportError, errString);
		return NULL;
	}
#ifdef USE_DYLD_GLOBAL_NAMESPACE
	if (!NSIsSymbolNameDefined(funcname)) {
		/* UnlinkModule() isn't implemented in current versions, but calling it does no harm */
		NSUnLinkModule(newModule, FALSE);
		PyErr_Format(PyExc_ImportError,
				 "Loaded module does not contain symbol %.200s",
				 funcname);
		return NULL;
	}
	theSym = NSLookupAndBindSymbol(funcname);
#else
	theSym = NSLookupSymbolInModule(newModule, funcname);
	if ( theSym == NULL ) {
		NSUnLinkModule(newModule, FALSE);
		PyErr_Format(PyExc_ImportError,
				 "Loaded module does not contain symbol %.200s",
				 funcname);
		return NULL;
	}
#endif
	p = (dl_funcptr)NSAddressOfSymbol(theSym);
	return p;
}
Esempio n. 15
0
wxString GetApplicationPath()
{
  static bool found = false;
  static wxString path;

  if (!found)
  {
/* Windows */
#ifdef __WXMSW__
    wxChar buf[512] = wxT("");
    GetModuleFileName(NULL, buf, 511);
    path = wxString(buf, wxConvUTF8);

/* UNIX & MAC*/
#else
    wxString argv0;

# ifdef __WXMAC__		
    if (NSIsSymbolNameDefined("__NSGetExecutablePath"))
    {
      char buf[512];
      size_t bufLen = 512;
      buf[0] = 0;
      ((NSGetExecutablePathProcPtr) NSAddressOfSymbol(NSLookupAndBindSymbol("__NSGetExecutablePath")))(buf, &bufLen);
      wxString strBuf = wxString();
      size_t actualBuflen = strlen(buf);
      if (actualBuflen > 0) {
        // FIXME: we *assume* that the NS stuff returns utf-8 encoded strings
        path = wxString(buf, wxConvUTF8);
        found=true;
        return path;
      }
    }
# endif

    argv0 = wxTheApp->argv[0];

    /* check absolute path */
    if (wxIsAbsolutePath(argv0)) {
        path = argv0;
    }
    else {
      /* check relative path */
      wxString fname = wxGetCwd() + wxFILE_SEP_PATH + argv0;
      if (wxFileExists(fname)) {
        path = fname;
      } else {
        /* find on PATH */
        wxPathList pathlist;
        pathlist.AddEnvList(wxT("PATH"));
        path = pathlist.FindAbsoluteValidPath(argv0);
      }
    }

    wxFileName filename(path);
    filename.Normalize();
    path = filename.GetFullPath();
#endif

    found = true;
  }
  return path;
}
Esempio n. 16
0
APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, 
                                      apr_dso_handle_t *handle, 
                                      const char *symname)
{
#if defined(DSO_USE_SHL)
    void *symaddr = NULL;
    int status;

    errno = 0;
    status = shl_findsym((shl_t *)&handle->handle, symname, TYPE_PROCEDURE, &symaddr);
    if (status == -1 && errno == 0) /* try TYPE_DATA instead */
        status = shl_findsym((shl_t *)&handle->handle, symname, TYPE_DATA, &symaddr);
    if (status == -1)
        return APR_ESYMNOTFOUND;
    *ressym = symaddr;
    return APR_SUCCESS;

#elif defined(DSO_USE_DYLD)
    void *retval = NULL;
    NSSymbol symbol;
    char *symname2 = (char*)malloc(sizeof(char)*(strlen(symname)+2));
    sprintf(symname2, "_%s", symname);
#ifdef NSLINKMODULE_OPTION_PRIVATE
    if (handle->handle == DYLD_LIBRARY_HANDLE) {
        symbol = NSLookupAndBindSymbol(symname2);
    }
    else {
        symbol = NSLookupSymbolInModule((NSModule)handle->handle, symname2);
    }
#else
    symbol = NSLookupAndBindSymbol(symname2);
#endif
    free(symname2);
    if (symbol == NULL) {
        handle->errormsg = "undefined symbol";
	return APR_ESYMNOTFOUND;
    }
    retval = NSAddressOfSymbol(symbol);
    if (retval == NULL) {
        handle->errormsg = "cannot resolve symbol";
	return APR_ESYMNOTFOUND;
    }
    *ressym = retval;
    return APR_SUCCESS;
#elif defined(DSO_USE_DLFCN)

#if defined(DLSYM_NEEDS_UNDERSCORE)
    void *retval;
    char *symbol = (char*)malloc(sizeof(char)*(strlen(symname)+2));
    sprintf(symbol, "_%s", symname);
    retval = dlsym(handle->handle, symbol);
    free(symbol);
#elif defined(SEQUENT) || defined(SNI)
    void *retval = dlsym(handle->handle, (char *)symname);
#else
    void *retval = dlsym(handle->handle, symname);
#endif /* DLSYM_NEEDS_UNDERSCORE */

    if (retval == NULL) {
        handle->errormsg = dlerror();
        return APR_ESYMNOTFOUND;
    }

    *ressym = retval;
    
    return APR_SUCCESS;
#endif /* DSO_USE_x */
}
Esempio n. 17
0
const void*
dlopen(const char* filename, int flags)
{
    static char has_callback = 0;
    if (!has_callback) {
        _dyld_register_func_for_add_image(dlshim_image_callback);
    }
    if (!filename) {
        return &dl_self;
    } else {
        const struct mach_header* img = NULL;
        if (!img)
            img = NSAddImage(filename, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
        if (!img)
            img = NSAddImage(filename,
                             NSADDIMAGE_OPTION_RETURN_ON_ERROR |
                             NSADDIMAGE_OPTION_WITH_SEARCHING);
        if (!img) {
            NSObjectFileImage fileImage;
            callback_count = 0;
            last_header = NULL;
            if (NSCreateObjectFileImageFromFile(filename, &fileImage)
                == NSObjectFileImageSuccess) {
                NSLinkModule(fileImage, filename,
                             NSLINKMODULE_OPTION_BINDNOW |
                             ((flags & RTLD_GLOBAL)?NSLINKMODULE_OPTION_PRIVATE:0) |
                             NSLINKMODULE_OPTION_RETURN_ON_ERROR);
                if (callback_count && last_header)
                    img = last_header;
            }
        }
        if (!img) {
            NSObjectFileImage fileImage;
            int i, maxi;
            const char* prefixfilename;
            maxi = lib_path_count();
            for (i = 0; i < maxi && !img; i++) {
                prefixfilename = lib_path_prefixify(i, filename);
                callback_count = 0;
                last_header = NULL;
                if (NSCreateObjectFileImageFromFile(prefixfilename, &fileImage)
                    == NSObjectFileImageSuccess) {
                    NSLinkModule(fileImage, filename,
                                 NSLINKMODULE_OPTION_BINDNOW |
                                 ((flags & RTLD_GLOBAL)?NSLINKMODULE_OPTION_PRIVATE:0) |
                                 NSLINKMODULE_OPTION_RETURN_ON_ERROR);
                    if (callback_count && last_header)
                        img = last_header;
                }
            }
        }
        if (img) {
            if (flags & RTLD_NOW) {
                NSLookupSymbolInImage(img, "",
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY |
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
            }
            if (NSIsSymbolNameDefinedInImage(img, "__init")) {
                NSSymbol initsymbol;
                void (*initfunc) (void);
                initsymbol = NSLookupSymbolInImage(img, "__init", 0);
                initfunc = NSAddressOfSymbol(initsymbol);
                initfunc();
            }
        } else
            last_error = DLOPEN_ERROR;
        return img;
    }
}
Esempio n. 18
0
void * Instance_Module_Load(const char * libLocation, const char * name, void ** Load, void ** Unload)
{
   char fileName[MAX_LOCATION];
   char extension[MAX_EXTENSION];
   void * library = null;
#if defined(__unix__) || defined(__APPLE__)
   int attempts = 0;
   char * paths[] = { null, "/usr/lib/ec/lib", "/usr/lib32/ec/lib" };
#endif

   *Load = null;
   *Unload = null;

#if defined(__WIN32__)
   strcpy(fileName, name);
   GetExtension(fileName, extension);
   if(!extension[0])
      strcat(fileName, ".dll");

   {
      uint16 _wfileName[MAX_LOCATION];
      UTF8toUTF16Buffer(fileName, _wfileName, MAX_LOCATION);
      library = LoadLibraryW(_wfileName);
   }
   if(library)
   {
#ifdef _WIN64
      *Load = (void *)GetProcAddress(library, "__ecereDll_Load");
      *Unload = (void *)GetProcAddress(library, "__ecereDll_Unload");
#else
      *Load = (void *)GetProcAddress(library, "__ecereDll_Load@4");
      *Unload = (void *)GetProcAddress(library, "__ecereDll_Unload@4");
#endif
      if(!*Load)
         FreeLibrary(library);
   }
#elif defined(__unix__) || defined(__APPLE__)
   if(libLocation || strchr(name, '/'))
      strcpy(fileName, libLocation ? libLocation : "");
   else
      strcpy(fileName, "lib");
   strcat(fileName, name);
   GetExtension(fileName, extension);
   if(!extension[0])
#if defined(__APPLE__)
      strcat(fileName, ".dylib");
#else
      strcat(fileName, ".so");
#endif

#if !defined(__EMSCRIPTEN__)
   // dlerror();
   library = dlopen(fileName, RTLD_LAZY);
   // if(!library)
      // printf("Error opening %s: %s", fileName, dlerror());
#endif
   while(!library && attempts < sizeof(paths)/sizeof(paths[0]))
   {
      if(paths[attempts])
         strcpy(fileName, paths[attempts++]);
      else
      {
         attempts++;
#ifdef DEB_HOST_MULTIARCH
         strcpy(fileName, DEB_HOST_MULTIARCH);
         strcat(fileName, "/ec/lib");
#else
         continue;
#endif
      }
      strcat(fileName, name);
      GetExtension(fileName, extension);
      if(!extension[0])
#if defined(__APPLE__)
         strcat(fileName, ".dylib");
#else
         strcat(fileName, ".so");
#endif
#if !defined(__EMSCRIPTEN__)
      library = dlopen(fileName, RTLD_LAZY);
#endif
   }

   if(library)
   {
      *Load = dlsym(library, "__ecereDll_Load");
      *Unload = dlsym(library, "__ecereDll_Unload");
#if !defined(__EMSCRIPTEN__)
      if(!*Load)
         dlclose(library);
#endif
   }
#elif defined(__APPLE__)
   if(libLocation || strchr(name, '/'))
      strcpy(fileName, libLocation ? libLocation : "");
   else
      strcpy(fileName, "lib");
   strcat(fileName, name);
   GetExtension(fileName, extension);
   if(!extension[0])
      strcat(fileName, ".dylib");
   {
      NSObjectFileImage *fileImage;
      NSObjectFileImageReturnCode returnCode = NSCreateObjectFileImageFromFile(fileName, &fileImage);

      if(returnCode == NSObjectFileImageSuccess)
      {
         printf("NSObjectFileImageSuccess!\n");
         library = NSLinkModule(fileImage,fileName,
              NSLINKMODULE_OPTION_RETURN_ON_ERROR
            | NSLINKMODULE_OPTION_PRIVATE);
         // NSDestroyObjectFileImage(fileImage);
         if(library)
         {
            *Load = NSAddressOfSymbol(NSLookupSymbolInModule(library, "__ecereDll_Load"));
            *Unload = NSAddressOfSymbol(NSLookupSymbolInModule(library, "__ecereDll_Unload"));
            if(!*Load)
            {
               NSUnLinkModule(library, 0);
            }
            else
               printf("Found Load!\n");
         }
      }
      else
         printf("No Success :(\n");
   }
#endif
   return library;
}
Esempio n. 19
0
int main()
{
// NSCreateObjectFileImageFromMemory is only available on Mac OS X - not iPhone OS
#if __MAC_OS_X_VERSION_MIN_REQUIRED
	NSObjectFileImage ofi;
	if ( NSCreateObjectFileImageFromFile("test.bundle", &ofi) != NSObjectFileImageSuccess ) {
		FAIL("NSCreateObjectFileImageFromFile failed");
		return 0;
	}

	NSModule mod = NSLinkModule(ofi, "test.bundle", NSLINKMODULE_OPTION_NONE);
	if ( mod == NULL ) {
		FAIL("NSLinkModule failed");
		return 0;
	}

	NSSymbol sym = NSLookupSymbolInModule(mod, "_setValue");
	if ( sym == NULL ) {
		FAIL("NSLookupSymbolInModule failed");
		return 0;
	}

	setter func = NSAddressOfSymbol(sym);
	(*func)(1);
	//fprintf(stderr, "address of foo() = %p in bundle first load %p\n", func, mod);


	NSModule mod2 = NSLinkModule(ofi, "test2.bundle", NSLINKMODULE_OPTION_NONE);
	if ( mod2 == NULL ) {
		NSLinkEditErrors c; int errorNumber; const char* fileName; const char* errorString;
		NSLinkEditError(&c, &errorNumber, &fileName, &errorString);
		FAIL("2nd NSLinkModule failed: %s", errorString);
		return 0;
	}
	if ( mod == mod2 ) {
		FAIL("2nd NSLinkModule return same function address as first");
		return 0;
	}

	NSSymbol sym2getter = NSLookupSymbolInModule(mod2, "_getValue");
	if ( sym2getter == NULL ) {
		FAIL("2nd NSLookupSymbolInModule failed");
		return 0;
	}
	getter func2getter = NSAddressOfSymbol(sym2getter);
	if ( (*func2getter)() != 0 ) {
		FAIL("_getValue() on second link returned non-zero");
		return 0;
	}

	NSSymbol sym2 = NSLookupSymbolInModule(mod2, "_setValue");
	if ( sym2 == NULL ) {
		FAIL("2nd NSLookupSymbolInModule failed");
		return 0;
	}
	setter func2 = NSAddressOfSymbol(sym2);
	(*func2)(2);
	
	//fprintf(stderr, "address of foo() = %p in bundle second load %p\n", func2, mod2);
	if ( func == func2 ) {
		FAIL("2nd NSAddressOfSymbol return same function address as 1st");
		return 0;
	}
	
	
	NSModule mod3 = NSLinkModule(ofi, "test3.bundle", NSLINKMODULE_OPTION_NONE);
	if ( mod3 == NULL ) {
		FAIL("3rd NSLinkModule failed");
		return 0;
	}
	if ( mod3 == mod ) {
		FAIL("3rd NSLinkModule return same function address as 1st");
		return 0;
	}
	if ( mod3 == mod2 ) {
		FAIL("3rd NSLinkModule return same function address as 2nd");
		return 0;
	}

   NSSymbol sym3 = NSLookupSymbolInModule(mod3, "_setValue");
	if ( sym3 == NULL ) {
		FAIL("3rd NSLookupSymbolInModule failed");
		return 0;
	}
	setter func3 = NSAddressOfSymbol(sym3);
	(*func3)(3);
	//fprintf(stderr, "address of foo() = %p in bundle third load %p\n", func3, mod3);
	if ( func3 == func ) {
		FAIL("3rd NSAddressOfSymbol return same function address as 1st");
		return 0;
	}
	if ( func3 == func2 ) {
		FAIL("3rd NSAddressOfSymbol return same function address as 2nd");
		return 0;
	}
		
	if ( !NSUnLinkModule(mod, NSUNLINKMODULE_OPTION_NONE) ) {
		FAIL("NSUnLinkModule failed");
		return 0;
	}

	if ( !NSUnLinkModule(mod3, NSUNLINKMODULE_OPTION_NONE) ) {
		FAIL("3rd NSUnLinkModule failed");
		return 0;
	}
	
	if ( !NSUnLinkModule(mod2, NSUNLINKMODULE_OPTION_NONE) ) {
		FAIL("2nd NSUnLinkModule failed");
		return 0;
	}
	
	// now link again after unlinking everything
	NSModule mod4 = NSLinkModule(ofi, "test4.bundle", NSLINKMODULE_OPTION_NONE);
	if ( mod4 == NULL ) {
		FAIL("4th NSLinkModule failed");
		return 0;
	}

	// check that this is really a new copy by verifying the getValue() returns zero
	NSSymbol sym4getter = NSLookupSymbolInModule(mod4, "_getValue");
	if ( sym4getter == NULL ) {
		FAIL("4th NSLookupSymbolInModule failed");
		return 0;
	}
	getter func4getter = NSAddressOfSymbol(sym4getter);
	if ( (*func4getter)() != 0 ) {
		FAIL("_getValue() on fourth link returned non-zero");
		return 0;
	}
	
	if ( !NSUnLinkModule(mod4, NSUNLINKMODULE_OPTION_NONE) ) {
		FAIL("4th NSUnLinkModule failed");
		return 0;
	}
	
	
	if ( !NSDestroyObjectFileImage(ofi) ) {
		FAIL("NSDestroyObjectFileImage failed");
		return 0;
	}
#endif

	PASS("bundle-multi-link");
	return 0;
}
Esempio n. 20
0
int
Tcl_MacOSXOpenVersionedBundleResources(
    Tcl_Interp *interp,
    const char *bundleName,
    const char *bundleVersion,
    int hasResourceFile,
    int maxPathLen,
    char *libraryPath)
{
#ifdef HAVE_COREFOUNDATION
    CFBundleRef bundleRef, versionedBundleRef = NULL;
    CFStringRef bundleNameRef;
    CFURLRef libURL;

    libraryPath[0] = '\0';

    bundleNameRef = CFStringCreateWithCString(NULL, bundleName,
	    kCFStringEncodingUTF8);

    bundleRef = CFBundleGetBundleWithIdentifier(bundleNameRef);
    CFRelease(bundleNameRef);

    if (bundleVersion && bundleRef) {
	/*
	 * Create bundle from bundleVersion subdirectory of 'Versions'.
	 */

	CFURLRef bundleURL = CFBundleCopyBundleURL(bundleRef);

	if (bundleURL) {
	    CFStringRef bundleVersionRef = CFStringCreateWithCString(NULL,
		    bundleVersion, kCFStringEncodingUTF8);

	    if (bundleVersionRef) {
		CFStringRef bundleTailRef = CFURLCopyLastPathComponent(
			bundleURL);

		if (bundleTailRef) {
		    if (CFStringCompare(bundleTailRef, bundleVersionRef, 0) ==
			    kCFCompareEqualTo) {
			versionedBundleRef = (CFBundleRef) CFRetain(bundleRef);
		    }
		    CFRelease(bundleTailRef);
		}
		if (!versionedBundleRef) {
		    CFURLRef versURL = CFURLCreateCopyAppendingPathComponent(
			    NULL, bundleURL, CFSTR("Versions"), TRUE);

		    if (versURL) {
			CFURLRef versionedBundleURL =
				CFURLCreateCopyAppendingPathComponent(
				NULL, versURL, bundleVersionRef, TRUE);
			if (versionedBundleURL) {
			    versionedBundleRef = CFBundleCreate(NULL,
				    versionedBundleURL);
			    CFRelease(versionedBundleURL);
			}
			CFRelease(versURL);
		    }
		}
		CFRelease(bundleVersionRef);
	    }
	    CFRelease(bundleURL);
	}
	if (versionedBundleRef) {
	    bundleRef = versionedBundleRef;
	}
    }

    if (bundleRef) {
	if (hasResourceFile) {
	    /*
	     * Dynamically acquire address for CFBundleOpenBundleResourceMap
	     * symbol, since it is only present in full CoreFoundation on Mac
	     * OS X and not in CFLite on pure Darwin.
	     */

	    static int initialized = FALSE;
	    static short (*openresourcemap)(CFBundleRef) = NULL;

	    if (!initialized) {
#if TCL_DYLD_USE_DLFCN
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1040
		if (tclMacOSXDarwinRelease >= 8)
#endif
		{
		    const char *errMsg = nil;
		    openresourcemap = dlsym(RTLD_NEXT,
			    "CFBundleOpenBundleResourceMap");
		    if (!openresourcemap) {
			errMsg = dlerror();
			TclLoadDbgMsg("dlsym() failed: %s", errMsg);
		    }
		}
		if (!openresourcemap)
#endif
		{
#if TCL_DYLD_USE_NSMODULE
		    NSSymbol nsSymbol = NULL;
		    if (NSIsSymbolNameDefinedWithHint(
			    "_CFBundleOpenBundleResourceMap",
			    "CoreFoundation")) {
			nsSymbol = NSLookupAndBindSymbolWithHint(
				"_CFBundleOpenBundleResourceMap",
				"CoreFoundation");
			if (nsSymbol) {
			    openresourcemap = NSAddressOfSymbol(nsSymbol);
			}
		    }
#endif
		}
		initialized = TRUE;
	    }

	    if (openresourcemap) {
		short refNum;

		refNum = openresourcemap(bundleRef);
	    }
	}

	libURL = CFBundleCopyResourceURL(bundleRef, CFSTR("Scripts"),
		NULL, NULL);

	if (libURL) {
	    /*
	     * FIXME: This is a quick fix, it is probably not right for
	     * internationalization.
	     */

	    CFURLGetFileSystemRepresentation(libURL, TRUE,
		    (unsigned char*) libraryPath, maxPathLen);
	    CFRelease(libURL);
	}
	if (versionedBundleRef) {
	    CFRelease(versionedBundleRef);
	}
    }

    if (libraryPath[0]) {
	return TCL_OK;
    } else {
	return TCL_ERROR;
    }
#else  /* HAVE_COREFOUNDATION */
    return TCL_ERROR;
#endif /* HAVE_COREFOUNDATION */
}
Esempio n. 21
0
GdkGLProc
gdk_gl_get_proc_address (const char *proc_name)
{
  typedef GdkGLProc (*__glXGetProcAddressProc) (const GLubyte *);
  static __glXGetProcAddressProc glx_get_proc_address = (__glXGetProcAddressProc) -1;
  const char *image_name;
  static const struct mach_header *libgl_image = NULL;
  static const struct mach_header *libglu_image = NULL;
  NSSymbol symbol;
  char *symbol_name;
  GdkGLProc proc_address;

  GDK_GL_NOTE_FUNC ();

  if (strncmp ("glu", proc_name, 3) != 0)
    {
      /* libGL */

      if (libgl_image == NULL)
        {
          image_name = g_getenv ("GDK_GL_LIBGL_PATH");
          if (image_name == NULL)
            image_name = _GDK_GL_LIBGL_PATH;

          GDK_GL_NOTE (MISC, g_message (" - Add Mach-O image %s", image_name));

          libgl_image = NSAddImage (image_name, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
          if (libgl_image == NULL)
            {
              g_warning ("Cannot add Mach-O image %s", image_name);
              return NULL;
            }
        }

      if (glx_get_proc_address == (__glXGetProcAddressProc) -1)
        {
          /*
           * Look up glXGetProcAddress () function.
           */

          symbol = NSLookupSymbolInImage (libgl_image,
                                          "_glXGetProcAddress",
                                          NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                          NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
          if (symbol == NULL)
            {
              symbol = NSLookupSymbolInImage (libgl_image,
                                              "_glXGetProcAddressARB",
                                              NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                              NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
              if (symbol == NULL)
                {
                  symbol = NSLookupSymbolInImage (libgl_image,
                                                  "_glXGetProcAddressEXT",
                                                  NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                                  NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
                }
            }
          GDK_GL_NOTE (MISC, g_message (" - glXGetProcAddress () - %s",
                                        symbol ? "supported" : "not supported"));
          if (symbol != NULL)
            glx_get_proc_address = NSAddressOfSymbol (symbol);
          else
            glx_get_proc_address = NULL;
        }

      /* Try glXGetProcAddress () */

      if (glx_get_proc_address != NULL)
        {
          proc_address = glx_get_proc_address (proc_name);
          GDK_GL_NOTE (IMPL, g_message (" ** glXGetProcAddress () - %s",
                                        proc_address ? "succeeded" : "failed"));
          if (proc_address != NULL)
            return proc_address;
        }

      /* Try Mach-O dyld */

      symbol_name = g_strconcat ("_", proc_name, NULL);

      symbol = NSLookupSymbolInImage (libgl_image,
                                      symbol_name,
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
      GDK_GL_NOTE (MISC, g_message (" - NSLookupSymbolInImage () - %s",
                                    symbol ? "succeeded" : "failed"));

      g_free (symbol_name);

      if (symbol != NULL)
        return NSAddressOfSymbol (symbol);
    }
  else
    {
      /* libGLU */

      if (libglu_image == NULL)
        {
          image_name = g_getenv ("GDK_GL_LIBGLU_PATH");
          if (image_name == NULL)
            image_name = _GDK_GL_LIBGLU_PATH;

          GDK_GL_NOTE (MISC, g_message (" - Add Mach-O image %s", image_name));

          libglu_image = NSAddImage (image_name, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
          if (libglu_image == NULL)
            {
              g_warning ("Cannot add Mach-O image %s", image_name);
              return NULL;
            }
        }

      symbol_name = g_strconcat ("_", proc_name, NULL);

      symbol = NSLookupSymbolInImage (libglu_image,
                                      symbol_name,
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
      GDK_GL_NOTE (MISC, g_message (" - NSLookupSymbolInImage () - %s",
                                    symbol ? "succeeded" : "failed"));

      g_free (symbol_name);

      if (symbol != NULL)
        return NSAddressOfSymbol (symbol);
    }

  return NULL;
}