/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 1, or (at your option)
** any later version.

** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.

** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/*
 * Author : Alexandre Parenteau <aubonbeurre@hotmail.com> --- February 2001
 */

/*
 * TclGlue.mac.cpp --- glue to the TCL language specific to mac/carbon
 */

#include "stdafx.h"

#if qCarbon

#ifndef NEW
#define NEW new
#endif

#include "TclGlue.mac.h"
#include <CFBundle.h>
#include <stdlib.h>
#include <string.h>

#if 1 // TARGET_RT_MAC_CFM
// our app on OSX is CFM, while TCL is mach-o. We need to re-encode the function pointer
// we give to the mach-o code
struct _CompatConnectID
{
	CFURLRef		bundleURL;
	CFBundleRef		myBundle;
};

static ProcPtr getSymFunction(CompatConnectID connID, const Str255 name)
{
	long symCount;
	Ptr symAddr;
	int i;
	OSErr err = CountSymbols(connID, &symCount);
	if(err != noErr)
		return 0L;
	
	for(i = 0; i < symCount; i++)
	{
		CFragSymbolClass symClass;
		Str255 symName;
		err = GetIndSymbol(connID, i, symName, &symAddr, &symClass);
		if(err != noErr)
			return 0L;
		if(memcmp(symName, name, name[0]) == 0)
			break;
	}
	if(i == symCount)
		return 0L;
	return (ProcPtr)symAddr;
}

int CarbonCompatLoadLibrary(CompatConnectID * connID, const char *name_dll)
{
	if(connID == 0L)
		return 0;

	if (UEnvironment::GetOSVersion() < 0x1000)
	{
		OSErr err;
		Ptr mainAddr;
		Str255 errMessage;
		Str255 pname;

		c2pstrcpy(pname, name_dll);
		err = GetSharedLibrary(pname, kPowerPCCFragArch, kPrivateCFragCopy, connID, &mainAddr, errMessage);
		return err == noErr;
	}
	else
	{
		*connID = 0L;

		 *connID = (CompatConnectID)malloc(sizeof(_CompatConnectID));
		
		struct _CompatConnectID *c = (struct _CompatConnectID *)*connID;
		
		if(c == 0L)
			return 0;

		c->bundleURL = 0L;
		c->myBundle = 0L;

		CFStringRef s = CFStringCreateWithCString(0L, name_dll, kCFStringEncodingMacRoman);
		if(s == 0L)
			goto fail;
		
		c->bundleURL	= CFURLCreateWithFileSystemPath(0L, s, kCFURLPOSIXPathStyle, false );
		if(c->bundleURL == 0L)
			goto fail;

		c->myBundle	= CFBundleCreate(0L, c->bundleURL );
		if(c->myBundle == 0L)
			goto fail;

		if(!CFBundleLoadExecutable( c->myBundle ))
			goto fail;

		CFRelease( s );
		return 1;
	fail:
		if(s != 0L)
			CFRelease( s );
		if(c != 0L)
		{
			if(c->bundleURL != 0L)
				CFRelease( c->bundleURL );
			if(c->myBundle != 0L)
				CFRelease( c->myBundle );
			*connID = 0L;
			free(c);
		}
		return 0;
	}
}

int CarbonCompatCloseLibrary(CompatConnectID * connID)
{
	if(connID == 0L)
		return 0;

	if (UEnvironment::GetOSVersion() < 0x1000)
	{
		CloseConnection(connID);
	}
	else
	{
		struct _CompatConnectID *c = (struct _CompatConnectID *)*connID;
		if(c != 0L)
		{
			CFBundleUnloadExecutable( c->myBundle );
			CFRelease( c->bundleURL );
			CFRelease( c->myBundle );
			free(c);
		}
		*connID = 0L;
	}
	return 1;
}

void *_CarbonCompatCallLibrary(CompatConnectID connID, const char *name_func)
{
	if (UEnvironment::GetOSVersion() < 0x1000)
	{
		ProcPtr symAddr;
		Str255 pname;

		c2pstrcpy(pname, name_func);

		symAddr = getSymFunction(connID, pname);
		return symAddr;
	}
	else
	{
		CFStringRef s = CFStringCreateWithCString(0L, name_func, kCFStringEncodingMacRoman);
		if(s == 0L)
			return 0L;
		
		struct _CompatConnectID *c = (struct _CompatConnectID *)connID;
		void *ptr = CFBundleGetFunctionPointerForName(c->myBundle, s);
		CFRelease( s );

		return ptr;
	}
	
	return 0L;
}

#define CompatLoadLibrary CarbonCompatLoadLibrary
#define CompatCloseLibrary CarbonCompatCloseLibrary
#define _CompatCallLibrary _CarbonCompatCallLibrary

void *_tcl_cfm_macho(void *func)
{
	static UInt32 templ[6] = {0x3D800000, 0x618C0000, 0x800C0000, 0x804C0004, 0x7C0903A6, 0x4E800420};

	// nothing to do on OS9, cause we call a CFM code in this case
	if (UEnvironment::GetOSVersion() < 0x1000)
		return func;
	
#pragma message(" Memory leak here, fix me !")
	UInt32	*mfp = (UInt32*) NewPtr( sizeof(templ) );		//	Must later dispose of allocated memory
	if(mfp == 0L)
		return 0L;
	
    mfp[0] = templ[0] | ((UInt32)func >> 16);
    mfp[1] = templ[1] | ((UInt32)func & 0xFFFF);
    mfp[2] = templ[2];
    mfp[3] = templ[3];
    mfp[4] = templ[4];
    mfp[5] = templ[5];
    MakeDataExecutable( mfp, sizeof(templ) );
    
    return mfp;
}
#endif // TARGET_RT_MAC_CFM

#if 0 // TARGET_RT_MAC_MACHO
#include "AppConsole.h"
#include <mach-o/dyld.h>

typedef void *dl_funcptr;

static dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname, const char *pathname)
{
	dl_funcptr p = NULL;
	char funcname[258];

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

	/* This is also NeXT-specific. However, frameworks (the new style
	of shared library) and rld() can't be used in the same program;
	instead, you have to use dyld, which is mostly unimplemented. */
	{
		NSObjectFileImageReturnCode rc;
		NSObjectFileImage image;
		NSModule newModule;
		NSSymbol theSym;
		const char *errString;
	
		if (NSIsSymbolNameDefined(funcname)) {
			theSym = NSLookupAndBindSymbol(funcname);
			p = (dl_funcptr)NSAddressOfSymbol(theSym);
			return p;
		}
		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,
				NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR);
			if (!newModule)
				errString = "Failure linking new module";
		}
		if (errString != NULL) {
			cvs_err(errString);
			return NULL;
		}
		if (!NSIsSymbolNameDefined(funcname)) {
			/* UnlinkModule() isn't implemented in current versions, but calling it does no harm */
			NSUnLinkModule(newModule, FALSE);
			cvs_err("Loaded module does not contain symbol %.200s", funcname);
			return NULL;
		}
		theSym = NSLookupAndBindSymbol(funcname);
		p = (dl_funcptr)NSAddressOfSymbol(theSym);
 	}

	return p;
}

void *_tcl_cfm_macho(void *func)
{
    return func;
}

int CarbonCompatLoadLibrary(CompatConnectID * connID, const char *name_dll)
{
	NSObjectFileImageReturnCode rc;
	NSObjectFileImage image;
	NSModule newModule;
	NSSymbol theSym;
	const char *errString;

	*connID = 0L;
	
	rc = NSCreateObjectFileImageFromFile(name_dll, &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, name_dll,
			NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR);
		if (!newModule)
			errString = "Failure linking new module";
	}
	if (errString != NULL) {
		cvs_err(errString);
		return 0;
	}
	
	*connID = (CompatConnectID)newModule;
	
	return 1;
}

int CarbonCompatCloseLibrary(CompatConnectID * connID)
{
	if(connID == 0L || *connID == 0L)
		return 0;

	NSUnLinkModule((NSModule)*connID, FALSE);
	*connID = 0L;

	return 1;
}

void *_CarbonCompatCallLibrary(CompatConnectID connID, const char *name_func)
{
	dl_funcptr p = NULL;
	char funcname[258];

	sprintf(funcname, "_init%.200s", name_func);

	/* This is also NeXT-specific. However, frameworks (the new style
	of shared library) and rld() can't be used in the same program;
	instead, you have to use dyld, which is mostly unimplemented. */
	NSSymbol theSym;

	if (NSIsSymbolNameDefined(funcname)) {
		theSym = NSLookupAndBindSymbol(funcname);
		p = (dl_funcptr)NSAddressOfSymbol(theSym);
		return p;
	}
	
	return 0L;
}
#endif // TARGET_RT_MAC_MACHO

#endif // qCarbon
