Landed sourcepawn-1.2. The big changes:
authorDavid Anderson <dvander@alliedmods.net>
Fri Aug 15 05:22:26 2008 +0000 (2008-08-15)
changeset 2226d10b38524be3
parent 2225 7a32df26e85d
child 2227 adc25d75d0fa
Landed sourcepawn-1.2. The big changes:

1) JIT compilation/optimization now occurs per-function, and only when functions are first used. We're now officially a whole-method JIT rather than an AOT compiler (albiet, still a simple JIT). This has two implications: Functions are now much better abstracted internally, and loading a plugin is now much less expensive. If a function contains calls to other functions, THOSE functions are only compiled when they're invoked as well.

2) I've removed debug mode. We always show full backtraces now, as there was a very cheap way to implement this which really cleaned up everything. This is great for a number of reasons -- there's less code, the JIT is better designed, we don't need to relocate debug tables, and best of all we no longer have to tell users to enable debug mode at their own expense.
core/DebugReporter.cpp
core/DebugReporter.h
core/NativeOwner.cpp
core/NativeOwner.h
core/sourcemod.cpp
core/systems/PluginSys.cpp
core/systems/PluginSys.h
core/systems/ShareSys.cpp
knight/shared/KeCodeAllocator.cpp
knight/shared/KeCodeAllocator.h
knight/shared/KeCommon.cpp
knight/shared/KeCommon.h
knight/shared/KeHashTable.cpp
knight/shared/KeHashTable.h
knight/shared/KeLinking.h
knight/shared/KeLumpAllocator.cpp
knight/shared/KeLumpAllocator.h
knight/shared/KePageAllocator.cpp
knight/shared/KePageAllocator.h
knight/shared/KePlatform.h
knight/shared/KeSectorStack.h
knight/shared/KeStdTypes.h
knight/shared/KeVector.h
knight/shared/KnightAllocator.h
public/IPluginSys.h
public/jit/jit_helpers.h
public/jit/x86/x86_macros.h
public/sourcepawn/sp_file_headers.h
public/sourcepawn/sp_vm_api.h
public/sourcepawn/sp_vm_types.h
sourcepawn/jit/BaseRuntime.cpp
sourcepawn/jit/BaseRuntime.h
sourcepawn/jit/Makefile
sourcepawn/jit/engine2.cpp
sourcepawn/jit/engine2.h
sourcepawn/jit/jit_function.cpp
sourcepawn/jit/jit_function.h
sourcepawn/jit/jit_shared.h
sourcepawn/jit/jit_version.h
sourcepawn/jit/sp_vm_basecontext.cpp
sourcepawn/jit/sp_vm_engine.cpp
sourcepawn/jit/sp_vm_engine.h
sourcepawn/jit/sp_vm_function.cpp
sourcepawn/jit/sp_vm_function.h
sourcepawn/jit/x86/jit_x86.cpp
sourcepawn/jit/x86/jit_x86.h
sourcepawn/jit/x86/opcode_helpers.cpp
sourcepawn/jit/x86/opcode_helpers.h
sourcepawn/jit/x86/opcode_switch.inc
     1.1 --- a/core/DebugReporter.cpp	Sun Aug 10 05:39:25 2008 +0000
     1.2 +++ b/core/DebugReporter.cpp	Fri Aug 15 05:22:26 2008 +0000
     1.3 @@ -41,6 +41,18 @@
     1.4  	g_pSourcePawn->SetDebugListener(this);
     1.5  }
     1.6  
     1.7 +void DebugReport::OnDebugSpew(const char *msg, ...)
     1.8 +{
     1.9 +	va_list ap;
    1.10 +	char buffer[512];
    1.11 +
    1.12 +	va_start(ap, msg);
    1.13 +	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
    1.14 +	va_end(ap);
    1.15 +
    1.16 +	g_Logger.LogMessage("[SM] %s", buffer);
    1.17 +}
    1.18 +
    1.19  void DebugReport::GenerateError(IPluginContext *ctx, cell_t func_idx, int err, const char *message, ...)
    1.20  {
    1.21  	va_list ap;
     2.1 --- a/core/DebugReporter.h	Sun Aug 10 05:39:25 2008 +0000
     2.2 +++ b/core/DebugReporter.h	Fri Aug 15 05:22:26 2008 +0000
     2.3 @@ -43,6 +43,8 @@
     2.4  	void OnSourceModAllInitialized();
     2.5  public: // IDebugListener
     2.6  	void OnContextExecuteError(IPluginContext *ctx, IContextTrace *error);
     2.7 +	void OnDebugSpew(const char *msg, ...);
     2.8 +public:
     2.9  	void GenerateError(IPluginContext *ctx, cell_t func_idx, int err, const char *message, ...);
    2.10  	void GenerateCodeError(IPluginContext *ctx, uint32_t code_addr, int err, const char *message, ...);
    2.11  private:
     3.1 --- a/core/NativeOwner.cpp	Sun Aug 10 05:39:25 2008 +0000
     3.2 +++ b/core/NativeOwner.cpp	Fri Aug 15 05:22:26 2008 +0000
     3.3 @@ -2,6 +2,10 @@
     3.4  #include "ShareSys.h"
     3.5  #include "PluginSys.h"
     3.6  
     3.7 +CNativeOwner::CNativeOwner() : m_nMarkSerial(0)
     3.8 +{
     3.9 +}
    3.10 +
    3.11  void CNativeOwner::SetMarkSerial(unsigned int serial)
    3.12  {
    3.13  	m_nMarkSerial = serial;
     4.1 --- a/core/NativeOwner.h	Sun Aug 10 05:39:25 2008 +0000
     4.2 +++ b/core/NativeOwner.h	Fri Aug 15 05:22:26 2008 +0000
     4.3 @@ -31,6 +31,8 @@
     4.4  class CNativeOwner
     4.5  {
     4.6  public:
     4.7 +	CNativeOwner();
     4.8 +public:
     4.9  	virtual void DropEverything();
    4.10  public:
    4.11  	void AddNatives(const sp_nativeinfo_t *info);
     5.1 --- a/core/sourcemod.cpp	Sun Aug 10 05:39:25 2008 +0000
     5.2 +++ b/core/sourcemod.cpp	Fri Aug 15 05:22:26 2008 +0000
     5.3 @@ -76,6 +76,11 @@
     5.4  		notify();
     5.5  	}
     5.6  
     5.7 +	if (g_pSourcePawn2 != NULL)
     5.8 +	{
     5.9 +		g_pSourcePawn2->Shutdown();
    5.10 +	}
    5.11 +
    5.12  	g_pJIT->CloseLibrary();
    5.13  }
    5.14  
    5.15 @@ -188,6 +193,26 @@
    5.16  	g_pSourcePawn = getv1();
    5.17  	g_pSourcePawn2 = getv2();
    5.18  
    5.19 +	if (g_pSourcePawn2->GetAPIVersion() < 2)
    5.20 +	{
    5.21 +		g_pSourcePawn2 = NULL;
    5.22 +		if (error && maxlength)
    5.23 +		{
    5.24 +			snprintf(error, maxlength, "JIT version is out of date");
    5.25 +		}
    5.26 +		return false;
    5.27 +	}
    5.28 +
    5.29 +	if (!g_pSourcePawn2->Initialize())
    5.30 +	{
    5.31 +		g_pSourcePawn2 = NULL;
    5.32 +		if (error && maxlength)
    5.33 +		{
    5.34 +			snprintf(error, maxlength, "JIT could not be initialized");
    5.35 +		}
    5.36 +		return false;
    5.37 +	}
    5.38 +
    5.39  	g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
    5.40  	g_pSourcePawn2->SetProfiler(&g_Profiler);
    5.41  
     6.1 --- a/core/systems/PluginSys.cpp	Sun Aug 10 05:39:25 2008 +0000
     6.2 +++ b/core/systems/PluginSys.cpp	Fri Aug 15 05:22:26 2008 +0000
     6.3 @@ -447,7 +447,7 @@
     6.4  		return false;
     6.5  	}
     6.6  
     6.7 -	return m_pRuntime->IsDebugging();
     6.8 +	return true;
     6.9  }
    6.10  
    6.11  void CPlugin::LibraryActions(bool dropping)
    6.12 @@ -507,61 +507,6 @@
    6.13  	return m_ident;
    6.14  }
    6.15  
    6.16 -bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
    6.17 -{
    6.18 -	int err;
    6.19 -
    6.20 -	if (!IsRunnable())
    6.21 -	{
    6.22 -		if (error)
    6.23 -		{
    6.24 -			snprintf(error, maxlength, "Plugin is not runnable.");
    6.25 -		}
    6.26 -		return false;
    6.27 -	}
    6.28 -
    6.29 -	if (debug && IsDebugging())
    6.30 -	{
    6.31 -		if (error)
    6.32 -		{
    6.33 -			snprintf(error, maxlength, "Plugin is already in debug mode.");
    6.34 -		}
    6.35 -		return false;
    6.36 -	}
    6.37 -	else if (!debug && !IsDebugging())
    6.38 -	{
    6.39 -		if (error)
    6.40 -		{
    6.41 -			snprintf(error, maxlength, "Plugins is already in production mode.");
    6.42 -		}
    6.43 -		return false;
    6.44 -	}
    6.45 -
    6.46 -	ICompilation *co = g_pSourcePawn2->StartCompilation();
    6.47 -
    6.48 -	if (!co->SetOption("debug", (debug) ? "1" : "0"))
    6.49 -	{
    6.50 -		if (error)
    6.51 -		{
    6.52 -			snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
    6.53 -		}
    6.54 -		return false;
    6.55 -	}
    6.56 -
    6.57 -	if ((err = m_pRuntime->ApplyCompilationOptions(co)) != SP_ERROR_NONE)
    6.58 -	{
    6.59 -		if (error)
    6.60 -		{
    6.61 -			snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
    6.62 -		}
    6.63 -		return false;
    6.64 -	}
    6.65 -
    6.66 -	UpdateInfo();
    6.67 -
    6.68 -	return true;
    6.69 -}
    6.70 -
    6.71  bool CPlugin::IsRunnable()
    6.72  {
    6.73  	return (m_status <= Plugin_Paused) ? true : false;
    6.74 @@ -1057,7 +1002,7 @@
    6.75  	LoadRes res;
    6.76  
    6.77  	*wasloaded = false;
    6.78 -	if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
    6.79 +	if ((res=_LoadPlugin(&pl, path, true, type, error, maxlength)) == LoadRes_Failure)
    6.80  	{
    6.81  		delete pl;
    6.82  		return NULL;
    6.83 @@ -2195,14 +2140,7 @@
    6.84  				{
    6.85  					if (pl->GetStatus() == Plugin_Running)
    6.86  					{
    6.87 -						if (pl->IsDebugging())
    6.88 -						{
    6.89 -							g_RootMenu.ConsolePrint("  Status: running, debugging");
    6.90 -						}
    6.91 -						else
    6.92 -						{
    6.93 -							g_RootMenu.ConsolePrint("  Status: running");
    6.94 -						}
    6.95 +						g_RootMenu.ConsolePrint("  Status: running");
    6.96  					}
    6.97  					else
    6.98  					{
    6.99 @@ -2245,83 +2183,6 @@
   6.100  
   6.101  			return;
   6.102  		}
   6.103 -		else if (strcmp(cmd, "debug") == 0)
   6.104 -		{
   6.105 -			if (argcount < 5)
   6.106 -			{
   6.107 -				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
   6.108 -				return;
   6.109 -			}
   6.110 -
   6.111 -			CPlugin *pl;
   6.112 -			char *end;
   6.113 -			const char *arg = command.Arg(3);
   6.114 -			int id = strtol(arg, &end, 10);
   6.115 -
   6.116 -			if (*end == '\0')
   6.117 -			{
   6.118 -				pl = GetPluginByOrder(id);
   6.119 -				if (!pl)
   6.120 -				{
   6.121 -					g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
   6.122 -					return;
   6.123 -				}
   6.124 -			}
   6.125 -			else
   6.126 -			{
   6.127 -				char pluginfile[256];
   6.128 -				const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
   6.129 -				UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
   6.130 -
   6.131 -				if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
   6.132 -				{
   6.133 -					g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
   6.134 -					return;
   6.135 -				}
   6.136 -			}
   6.137 -
   6.138 -			int res;
   6.139 -			const char *mode = command.Arg(4);
   6.140 -			if ((res=strcmp("on", mode)) && strcmp("off", mode))
   6.141 -			{
   6.142 -				g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
   6.143 -				return;
   6.144 -			}
   6.145 -
   6.146 -			bool debug;
   6.147 -			if (!res)
   6.148 -			{
   6.149 -				debug = true;
   6.150 -			}
   6.151 -			else
   6.152 -			{
   6.153 -				debug = false;
   6.154 -			}
   6.155 -
   6.156 -			if (debug && pl->IsDebugging())
   6.157 -			{
   6.158 -				g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
   6.159 -				return;
   6.160 -			}
   6.161 -			else if (!debug && !pl->IsDebugging())
   6.162 -			{
   6.163 -				g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
   6.164 -				return;
   6.165 -			}
   6.166 -
   6.167 -			char error[256];
   6.168 -			if (pl->ToggleDebugMode(debug, error, sizeof(error)))
   6.169 -			{
   6.170 -				g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
   6.171 -				return;
   6.172 -			}
   6.173 -			else
   6.174 -			{
   6.175 -				g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
   6.176 -				g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
   6.177 -				return;
   6.178 -			}
   6.179 -		}
   6.180  		else if (strcmp(cmd, "refresh") == 0)
   6.181  		{
   6.182  			g_SourceMod.DoGlobalPluginLoads();
   6.183 @@ -2382,7 +2243,6 @@
   6.184  
   6.185  	/* Draw the main menu */
   6.186  	g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
   6.187 -	g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
   6.188  	g_RootMenu.DrawGenericOption("info", "Information about a plugin");
   6.189  	g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
   6.190  	g_RootMenu.DrawGenericOption("load", "Load a plugin");
   6.191 @@ -2398,13 +2258,12 @@
   6.192  {
   6.193  	List<CPlugin *>::iterator iter;
   6.194  	char filename[PLATFORM_MAX_PATH];
   6.195 -	bool debug, wasloaded;
   6.196 +	bool wasloaded;
   6.197  	PluginType ptype;
   6.198  	IPlugin *newpl;
   6.199  	int id = 1;
   6.200  
   6.201  	strcpy(filename, pl->m_filename);
   6.202 -	debug = pl->IsDebugging();
   6.203  	ptype = pl->GetType();
   6.204  
   6.205  	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
   6.206 @@ -2419,7 +2278,7 @@
   6.207  	{
   6.208  		return false;
   6.209  	}
   6.210 -	if (!(newpl=LoadPlugin(filename, debug, ptype, NULL, 0, &wasloaded)))
   6.211 +	if (!(newpl=LoadPlugin(filename, true, ptype, NULL, 0, &wasloaded)))
   6.212  	{
   6.213  		return false;
   6.214  	}
     7.1 --- a/core/systems/PluginSys.h	Sun Aug 10 05:39:25 2008 +0000
     7.2 +++ b/core/systems/PluginSys.h	Fri Aug 15 05:22:26 2008 +0000
     7.3 @@ -199,11 +199,6 @@
     7.4  	void Call_OnAllPluginsLoaded();
     7.5  
     7.6  	/**
     7.7 -	 * Toggles debug mode in the plugin
     7.8 -	 */
     7.9 -	bool ToggleDebugMode(bool debug, char *error, size_t maxlength);
    7.10 -
    7.11 -	/**
    7.12  	 * Returns true if a plugin is usable.
    7.13  	 */
    7.14  	bool IsRunnable();
     8.1 --- a/core/systems/ShareSys.cpp	Sun Aug 10 05:39:25 2008 +0000
     8.2 +++ b/core/systems/ShareSys.cpp	Fri Aug 15 05:22:26 2008 +0000
     8.3 @@ -413,9 +413,9 @@
     8.4  			else
     8.5  			{
     8.6  				/* See if this has already been marked as a dependent.
     8.7 -				* If it has, it means this relationship has already occurred, 
     8.8 -				* and there is no reason to do it again.
     8.9 -				*/
    8.10 +				 * If it has, it means this relationship has already occurred, 
    8.11 +				 * and there is no reason to do it again.
    8.12 +				 */
    8.13  				if (pEntry->owner != pPlugin 
    8.14  					&& pEntry->owner->GetMarkSerial() != g_mark_serial)
    8.15  				{
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/knight/shared/KeCodeAllocator.cpp	Fri Aug 15 05:22:26 2008 +0000
     9.3 @@ -0,0 +1,428 @@
     9.4 +#include <KePlatform.h>
     9.5 +#include <assert.h>
     9.6 +#include <string.h>
     9.7 +
     9.8 +#if defined KE_PLATFORM_WINDOWS
     9.9 +#include <windows.h>
    9.10 +#elif defined KE_PLATFORM_POSIX
    9.11 +#include <unistd.h>
    9.12 +#include <stdlib.h>
    9.13 +#include <sys/mman.h>
    9.14 +#else
    9.15 +#error "TODO"
    9.16 +#endif
    9.17 +
    9.18 +#include "KeCodeAllocator.h"
    9.19 +
    9.20 +#define ALIGNMENT	16
    9.21 +
    9.22 +using namespace Knight;
    9.23 +
    9.24 +struct KeFreedCode;
    9.25 +
    9.26 +/**
    9.27 + * Defines a region of memory that is made of pages. 
    9.28 + */
    9.29 +struct KeCodeRegion
    9.30 +{
    9.31 +	KeCodeRegion *next;
    9.32 +	unsigned char *block_start;
    9.33 +	unsigned char *block_pos;
    9.34 +	KeFreedCode *free_list;
    9.35 +	size_t total_size;
    9.36 +	size_t end_free;
    9.37 +	size_t total_free;
    9.38 +};
    9.39 +
    9.40 +/**
    9.41 + * Defines freed code.  We keep the size here because 
    9.42 + * when we touch the linked list we don't want to dirty pages.
    9.43 + */
    9.44 +struct KeFreedCode
    9.45 +{
    9.46 +	KeCodeRegion *region;
    9.47 +	unsigned char *block_start;
    9.48 +	size_t size;
    9.49 +	KeFreedCode *next;
    9.50 +};
    9.51 +
    9.52 +struct KeSecret
    9.53 +{
    9.54 +	KeCodeRegion *region;
    9.55 +	size_t size;
    9.56 +};
    9.57 +
    9.58 +class Knight::KeCodeCache
    9.59 +{
    9.60 +public:
    9.61 +	/**
    9.62 +	 * First region that is live for use.
    9.63 +	 */
    9.64 +	KeCodeRegion *first_live;
    9.65 +
    9.66 +	/**
    9.67 +	 * First region that is full but has free entries.
    9.68 +	 */
    9.69 +	KeCodeRegion *first_partial;
    9.70 +
    9.71 +	/**
    9.72 +	 * First region that is full.
    9.73 +	 */
    9.74 +	KeCodeRegion *first_full;
    9.75 +
    9.76 +	/**
    9.77 +	 * Page granularity and size.
    9.78 +	 */
    9.79 +	unsigned int page_size;
    9.80 +	unsigned int page_granularity;
    9.81 +
    9.82 +	/**
    9.83 +	 * This isn't actually for code, this is the node cache.
    9.84 +	 */
    9.85 +	KeCodeRegion *node_cache;
    9.86 +	KeFreedCode *free_node_list;
    9.87 +};
    9.88 +
    9.89 +KeCodeCache *Knight::KE_CreateCodeCache()
    9.90 +{
    9.91 +	KeCodeCache *cache;
    9.92 +
    9.93 +	cache = new KeCodeCache;
    9.94 +
    9.95 +	memset(cache, 0, sizeof(KeCodeCache));
    9.96 +
    9.97 +#if defined KE_PLATFORM_WINDOWS
    9.98 +	SYSTEM_INFO info;
    9.99 +
   9.100 +	GetSystemInfo(&info);
   9.101 +	cache->page_size = info.dwPageSize;
   9.102 +	cache->page_granularity = info.dwAllocationGranularity;
   9.103 +#else
   9.104 +	cache->page_size = cache->page_granularity = sysconf(_SC_PAGESIZE);
   9.105 +#endif
   9.106 +
   9.107 +	return cache;
   9.108 +}
   9.109 +
   9.110 +inline size_t MinAllocSize()
   9.111 +{
   9.112 +	size_t size;
   9.113 +
   9.114 +	size = sizeof(KeSecret);
   9.115 +	size += ALIGNMENT;
   9.116 +	size -= size % ALIGNMENT;
   9.117 +
   9.118 +	return size;
   9.119 +}
   9.120 +
   9.121 +inline size_t ke_GetAllocSize(size_t size)
   9.122 +{
   9.123 +	size += sizeof(KeSecret);
   9.124 +	size += ALIGNMENT;
   9.125 +	size -= size % ALIGNMENT;
   9.126 +
   9.127 +	return size;
   9.128 +}
   9.129 +
   9.130 +void *ke_AllocInRegion(KeCodeCache *cache,
   9.131 +					   KeCodeRegion **prev,
   9.132 +					   KeCodeRegion *region,
   9.133 +					   unsigned char *ptr,
   9.134 +					   size_t alloc_size,
   9.135 +					   bool is_live)
   9.136 +{
   9.137 +	KeSecret *secret;
   9.138 +
   9.139 +	/* Squirrel some info in the alloc. */
   9.140 +	secret = (KeSecret *)ptr;
   9.141 +	secret->region = region;
   9.142 +	secret->size = alloc_size;
   9.143 +	ptr += sizeof(KeSecret);
   9.144 +
   9.145 +	region->total_free -= alloc_size;
   9.146 +
   9.147 +	/* Check if we can't use the fast-path anymore. */
   9.148 +	if ((is_live && region->end_free < MinAllocSize())
   9.149 +		|| (!is_live && region->total_free < MinAllocSize()))
   9.150 +	{
   9.151 +		KeCodeRegion **start;
   9.152 +
   9.153 +		*prev = region->next;
   9.154 +
   9.155 +		/* Select the appropriate arena. */
   9.156 +		if (is_live)
   9.157 +		{
   9.158 +			if (region->total_free < MinAllocSize())
   9.159 +			{
   9.160 +				start = &cache->first_full;
   9.161 +			}
   9.162 +			else
   9.163 +			{
   9.164 +				start = &cache->first_partial;
   9.165 +			}
   9.166 +		}
   9.167 +		else
   9.168 +		{
   9.169 +			start = &cache->first_full;
   9.170 +		}
   9.171 +		
   9.172 +		region->next = *start;
   9.173 +		*start = region;
   9.174 +	}
   9.175 +
   9.176 +	return ptr;
   9.177 +}
   9.178 +
   9.179 +void *ke_AllocFromLive(KeCodeCache *cache, size_t size)
   9.180 +{
   9.181 +	void *ptr;
   9.182 +	size_t alloc_size;
   9.183 +	KeCodeRegion *region, **prev;
   9.184 +
   9.185 +	region = cache->first_live;
   9.186 +	prev = &cache->first_live;
   9.187 +	alloc_size = ke_GetAllocSize(size);
   9.188 +
   9.189 +	while (region != NULL)
   9.190 +	{
   9.191 +		if (region->end_free >= alloc_size)
   9.192 +		{
   9.193 +			/* Yay! We can do a simple alloc here. */
   9.194 +			ptr = ke_AllocInRegion(cache, prev, region, region->block_pos, alloc_size, true);
   9.195 +
   9.196 +			/* Update our counters. */
   9.197 +			region->block_pos += alloc_size;
   9.198 +			region->end_free -= alloc_size;
   9.199 +
   9.200 +			return ptr;
   9.201 +		}
   9.202 +		prev = &region->next;
   9.203 +		region = region->next;
   9.204 +	}
   9.205 +
   9.206 +	return NULL;
   9.207 +}
   9.208 +
   9.209 +void *ke_AllocFromPartial(KeCodeCache *cache, size_t size)
   9.210 +{
   9.211 +	void *ptr;
   9.212 +	size_t alloc_size;
   9.213 +	KeCodeRegion *region, **prev;
   9.214 +
   9.215 +	region = cache->first_partial;
   9.216 +	prev = &cache->first_partial;
   9.217 +	alloc_size = ke_GetAllocSize(size);
   9.218 +
   9.219 +	while (region != NULL)
   9.220 +	{
   9.221 +		if (region->total_free >= alloc_size)
   9.222 +		{
   9.223 +			KeFreedCode *node, **last;
   9.224 +
   9.225 +			assert(region->free_list != NULL);
   9.226 +
   9.227 +			last = &region->free_list;
   9.228 +			node = region->free_list;
   9.229 +			while (node != NULL)
   9.230 +			{
   9.231 +				if (node->size >= alloc_size)
   9.232 +				{
   9.233 +					/* Use this node */
   9.234 +					ptr = ke_AllocInRegion(cache, prev, region, node->block_start, alloc_size, false);
   9.235 +
   9.236 +					region->total_free -= node->size;
   9.237 +					*last = node->next;
   9.238 +
   9.239 +					/* Make sure bookkeepping is correct. */
   9.240 +					assert((region->free_list == NULL && region->total_free == 0)
   9.241 +						   || (region->free_list != NULL && region->total_free != 0));
   9.242 +
   9.243 +					/* Link us back into the free node list. */
   9.244 +					node->next = cache->free_node_list;
   9.245 +					cache->free_node_list = node->next;
   9.246 +
   9.247 +					return ptr;
   9.248 +				}
   9.249 +				last = &node->next;
   9.250 +				node = node->next;
   9.251 +			}
   9.252 +		}
   9.253 +		prev = &region->next;
   9.254 +		region = region->next;
   9.255 +	}
   9.256 +
   9.257 +	return NULL;
   9.258 +}
   9.259 +
   9.260 +KeCodeRegion *ke_AddRegionForSize(KeCodeCache *cache, size_t size)
   9.261 +{
   9.262 +	KeCodeRegion *region;
   9.263 +
   9.264 +	region = new KeCodeRegion;
   9.265 +
   9.266 +	size = ke_GetAllocSize(size);
   9.267 +	size += cache->page_granularity * 2;
   9.268 +	size -= size % cache->page_granularity;
   9.269 +
   9.270 +#if defined KE_PLATFORM_WINDOWS
   9.271 +	region->block_start = (unsigned char *)VirtualAlloc(NULL, size, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE);
   9.272 +#elif defined KE_PLATFORM_POSIX
   9.273 +	region->block_start = (unsigned char *)valloc(size);
   9.274 +	if (mprotect(region->block_start, size, PROT_READ|PROT_WRITE|PROT_EXEC) == -1)
   9.275 +	{
   9.276 +		free(region->block_start);
   9.277 +		delete region;
   9.278 +		return NULL;
   9.279 +	}
   9.280 +#else
   9.281 +#error "TODO"
   9.282 +#endif
   9.283 +
   9.284 +	if (region->block_start == NULL)
   9.285 +	{
   9.286 +		delete region;
   9.287 +		return NULL;
   9.288 +	}
   9.289 +
   9.290 +	region->block_pos = region->block_start;
   9.291 +	region->end_free = region->total_free = region->total_size = size;
   9.292 +	region->next = cache->first_live;
   9.293 +	cache->first_live = region;
   9.294 +	region->free_list = NULL;
   9.295 +
   9.296 +	return region;
   9.297 +}
   9.298 +
   9.299 +void *Knight::KE_AllocCode(KeCodeCache *cache, size_t size)
   9.300 +{
   9.301 +	void *ptr;
   9.302 +
   9.303 +	/* Check live easy-adds */
   9.304 +	if (cache->first_live != NULL)
   9.305 +	{
   9.306 +		if ((ptr = ke_AllocFromLive(cache, size)) != NULL)
   9.307 +		{
   9.308 +			return ptr;
   9.309 +		}
   9.310 +	}
   9.311 +	
   9.312 +	/* Try looking in the free lists */
   9.313 +	if (cache->first_partial != NULL)
   9.314 +	{
   9.315 +		if ((ptr = ke_AllocFromPartial(cache, size)) != NULL)
   9.316 +		{
   9.317 +			return ptr;
   9.318 +		}
   9.319 +	}
   9.320 +
   9.321 +	/* Create a new region */
   9.322 +	if (ke_AddRegionForSize(cache, size) == NULL)
   9.323 +	{
   9.324 +		return NULL;
   9.325 +	}
   9.326 +
   9.327 +	return ke_AllocFromLive(cache, size);
   9.328 +}
   9.329 +
   9.330 +KeFreedCode *ke_GetFreeNode(KeCodeCache *cache)
   9.331 +{
   9.332 +	KeFreedCode *ret;
   9.333 +
   9.334 +	if (cache->free_node_list != NULL)
   9.335 +	{
   9.336 +		ret = cache->free_node_list;
   9.337 +		cache->free_node_list = ret->next;
   9.338 +
   9.339 +		return ret;
   9.340 +	}
   9.341 +
   9.342 +	/* See if the current free node region has space. */
   9.343 +	if (cache->node_cache != NULL
   9.344 +		&& cache->node_cache->end_free >= sizeof(KeFreedCode))
   9.345 +	{
   9.346 +		ret = (KeFreedCode *)cache->node_cache->block_pos;
   9.347 +		cache->node_cache->block_pos += sizeof(KeFreedCode);
   9.348 +		cache->node_cache->total_free -= sizeof(KeFreedCode);
   9.349 +		cache->node_cache->end_free -= sizeof(KeFreedCode);
   9.350 +
   9.351 +		return ret;
   9.352 +	}
   9.353 +
   9.354 +	/* Otherwise, we need to alloc a new region. */
   9.355 +	KeCodeRegion *region = new KeCodeRegion;
   9.356 +	
   9.357 +	region->block_start = new unsigned char[cache->page_size / sizeof(KeFreedCode)];
   9.358 +	region->block_pos = region->block_start + sizeof(KeFreedCode);
   9.359 +	region->total_size = cache->page_size / sizeof(KeFreedCode);
   9.360 +	region->total_free = region->end_free = (region->total_size - sizeof(KeFreedCode));
   9.361 +	region->free_list = NULL;
   9.362 +	region->next = cache->node_cache;
   9.363 +	cache->node_cache = region;
   9.364 +
   9.365 +	return (KeFreedCode *)region->block_start;
   9.366 +}
   9.367 +
   9.368 +void Knight::KE_FreeCode(KeCodeCache *cache, void *code)
   9.369 +{
   9.370 +	KeSecret *secret;
   9.371 +	KeFreedCode *node;
   9.372 +	unsigned char *ptr;
   9.373 +	KeCodeRegion *region;
   9.374 +
   9.375 +	ptr = (unsigned char *)code;
   9.376 +	secret = (KeSecret *)(ptr - sizeof(KeSecret));
   9.377 +	region = secret->region;
   9.378 +	node = ke_GetFreeNode(cache);
   9.379 +	node->block_start = (unsigned char *)code;
   9.380 +	node->next = region->free_list;
   9.381 +	region->free_list = node;
   9.382 +	node->region = region;
   9.383 +	node->size = secret->size;
   9.384 +}
   9.385 +
   9.386 +KeCodeRegion *ke_DestroyRegion(KeCodeRegion *region)
   9.387 +{
   9.388 +	KeCodeRegion *next;
   9.389 +
   9.390 +	next = region->next;
   9.391 +
   9.392 +#if defined KE_PLATFORM_WINDOWS
   9.393 +	VirtualFree(region->block_start, 0, MEM_RELEASE);
   9.394 +#else
   9.395 +	free(region->block_start);
   9.396 +#endif
   9.397 +
   9.398 +	delete region;
   9.399 +
   9.400 +	return next;
   9.401 +}
   9.402 +
   9.403 +void ke_DestroyRegionChain(KeCodeRegion *first)
   9.404 +{
   9.405 +	while (first != NULL)
   9.406 +	{
   9.407 +		first = ke_DestroyRegion(first);
   9.408 +	}
   9.409 +}
   9.410 +
   9.411 +void Knight::KE_DestroyCodeCache(KeCodeCache *cache)
   9.412 +{
   9.413 +	/* Destroy every region and call it a day. */
   9.414 +	ke_DestroyRegionChain(cache->first_full);
   9.415 +	ke_DestroyRegionChain(cache->first_live);
   9.416 +	ke_DestroyRegionChain(cache->first_partial);
   9.417 +
   9.418 +	/* We use normal malloc for node cache regions */
   9.419 +	KeCodeRegion *region, *next;
   9.420 +	
   9.421 +	region = cache->node_cache;
   9.422 +	while (region != NULL)
   9.423 +	{
   9.424 +		next = region->next;
   9.425 +		delete [] region->block_start;
   9.426 +		delete region;
   9.427 +		region = next;
   9.428 +	}
   9.429 +	
   9.430 +	delete cache;
   9.431 +}
    10.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    10.2 +++ b/knight/shared/KeCodeAllocator.h	Fri Aug 15 05:22:26 2008 +0000
    10.3 @@ -0,0 +1,47 @@
    10.4 +#ifndef _INCLUDE_KNIGHT_KE_CODE_ALLOCATOR_H_
    10.5 +#define _INCLUDE_KNIGHT_KE_CODE_ALLOCATOR_H_
    10.6 +
    10.7 +#include <KeLinking.h>
    10.8 +#include <KeStdTypes.h>
    10.9 +
   10.10 +namespace Knight
   10.11 +{
   10.12 +	class KeCodeCache;
   10.13 +
   10.14 +	/**
   10.15 +	 * @brief Creates a new code cache/allocator.
   10.16 +	 *
   10.17 +	 * @return				New code cache allocator.
   10.18 +	 */
   10.19 +	extern KeCodeCache *KE_CreateCodeCache();
   10.20 +
   10.21 +	/**
   10.22 +	 * @brief Destroys a code cache allocator.
   10.23 +	 *
   10.24 +	 * @param cache			Code cache object.
   10.25 +	 */
   10.26 +	extern void KE_DestroyCodeCache(KeCodeCache *cache);
   10.27 +
   10.28 +	/**
   10.29 +	 * @brief Allocates code memory that is readable, writable, 
   10.30 +	 * and executable.
   10.31 +	 *
   10.32 +	 * The address returned wlil be aligned, minimally, on a 16-byte 
   10.33 +	 * boundary.
   10.34 +	 *
   10.35 +	 * @param cache			Code cache object.
   10.36 +	 * @param size			Amount of memory needed.
   10.37 +	 * @return				Address pointing to the memory.
   10.38 +	 */
   10.39 +	extern void *KE_AllocCode(KeCodeCache *cache, size_t size);
   10.40 +
   10.41 +	/**
   10.42 +	 * @brief Frees code memory.
   10.43 +	 *
   10.44 +	 * @param cache			Code cache object.
   10.45 +	 * @param code			Address of code memory.
   10.46 +	 */
   10.47 +	extern void KE_FreeCode(KeCodeCache *cache, void *code);
   10.48 +}
   10.49 +
   10.50 +#endif //_INCLUDE_KNIGHT_KE_CODE_ALLOCATOR_H_
    11.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    11.2 +++ b/knight/shared/KeCommon.cpp	Fri Aug 15 05:22:26 2008 +0000
    11.3 @@ -0,0 +1,33 @@
    11.4 +#include <stdio.h>
    11.5 +#include "KeCommon.h"
    11.6 +
    11.7 +using namespace Knight;
    11.8 +
    11.9 +size_t Knight::KE_PFormat(char *buffer, size_t maxlength, const char *fmt, ...)
   11.10 +{
   11.11 +	size_t len;
   11.12 +
   11.13 +	va_list ap;
   11.14 +	va_start(ap, fmt);
   11.15 +	len = KE_PFormatArgs(buffer, maxlength, fmt, ap);
   11.16 +	va_end(ap);
   11.17 +
   11.18 +	return len;
   11.19 +}
   11.20 +
   11.21 +size_t Knight::KE_PFormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list ap)
   11.22 +{
   11.23 +	size_t len;
   11.24 +	
   11.25 +	len = vsnprintf(buffer, maxlength, fmt, ap);
   11.26 +
   11.27 +	if (len >= maxlength)
   11.28 +	{
   11.29 +		buffer[maxlength - 1] = '\0';
   11.30 +		return (maxlength - 1);
   11.31 +	}
   11.32 +	else
   11.33 +	{
   11.34 +		return len;
   11.35 +	}
   11.36 +}
    12.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.2 +++ b/knight/shared/KeCommon.h	Fri Aug 15 05:22:26 2008 +0000
    12.3 @@ -0,0 +1,36 @@
    12.4 +#ifndef _INCLUDE_KNIGHT_KE_COMMON_UTILS_H_
    12.5 +#define _INCLUDE_KNIGHT_KE_COMMON_UTILS_H_
    12.6 +
    12.7 +#include <stddef.h>
    12.8 +#include <stdarg.h>
    12.9 +
   12.10 +namespace Knight
   12.11 +{
   12.12 +	/**
   12.13 +	 * @brief Formats a buffer with C platform rules.
   12.14 +	 *
   12.15 +	 * Unlink platform snprintf, this will never return nonsense values like -1.
   12.16 +	 *
   12.17 +	 * @param buffer			Buffer to store to.
   12.18 +	 * @param maxlength			Maximum length of buffer (including null terminator).
   12.19 +	 * @param fmt				printf() format string.
   12.20 +	 * @param ...				Formatting arguments.
   12.21 +	 * @return					Number of characters written.
   12.22 +	 */
   12.23 +	extern size_t KE_PFormat(char *buffer, size_t maxlength, const char *fmt, ...);
   12.24 +
   12.25 +	/**
   12.26 +	 * @brief Formats a buffer with C platform rules.
   12.27 +	 *
   12.28 +	 * Unlink platform snprintf, this will never return nonsense values like -1.
   12.29 +	 *
   12.30 +	 * @param buffer			Buffer to store to.
   12.31 +	 * @param maxlength			Maximum length of buffer (including null terminator).
   12.32 +	 * @param fmt				printf() format string.
   12.33 +	 * @param args				Formatting arguments.
   12.34 +	 * @return					Number of characters written.
   12.35 +	 */
   12.36 +	extern size_t KE_PFormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list args);
   12.37 +}
   12.38 +
   12.39 +#endif //_INCLUDE_KNIGHT_KE_COMMON_UTILS_H_
    13.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    13.2 +++ b/knight/shared/KeHashTable.cpp	Fri Aug 15 05:22:26 2008 +0000
    13.3 @@ -0,0 +1,409 @@
    13.4 +#include <KeHashTable.h>
    13.5 +
    13.6 +using namespace Knight;
    13.7 +
    13.8 +struct KeHashNode
    13.9 +{
   13.10 +	KeHashNode *next;
   13.11 +	uint32_t key_hash;
   13.12 +	const void *key;
   13.13 +	void *value;
   13.14 +};
   13.15 +
   13.16 +namespace Knight
   13.17 +{
   13.18 +	class KeHashTable
   13.19 +	{
   13.20 +	public:
   13.21 +		KeHashNode **buckets;
   13.22 +		uint32_t num_buckets;
   13.23 +		uint32_t shift;
   13.24 +		uint32_t num_entries;
   13.25 +		KeHashGenerator key_gen;
   13.26 +		KeHashMarshal key_m;
   13.27 +		KeHashMarshal val_m;
   13.28 +		ke_allocator_t *node_alloc;
   13.29 +		size_t key_offs;
   13.30 +		size_t val_offs;
   13.31 +		size_t node_size;
   13.32 +		uint32_t grow_limit;
   13.33 +		KeHashNode *free_list;
   13.34 +		bool keep_free_list;
   13.35 +	};
   13.36 +}
   13.37 +
   13.38 +void *ke_DefHashMalloc(ke_allocator_t *alloc, size_t amt)
   13.39 +{
   13.40 +	return malloc(amt);
   13.41 +}
   13.42 +
   13.43 +void ke_DefHashFree(ke_allocator_t *alloc, void *addr)
   13.44 +{
   13.45 +	free(addr);
   13.46 +}
   13.47 +
   13.48 +ke_allocator_t s_DefHashAllocator = 
   13.49 +{
   13.50 +	ke_DefHashMalloc,
   13.51 +	ke_DefHashFree,
   13.52 +	NULL
   13.53 +};
   13.54 +
   13.55 +KeHashTable *Knight::KE_CreateHashTable(
   13.56 +	uint32_t bits,
   13.57 +	KeHashGenerator key_gen,
   13.58 +	const KeHashMarshal *key_marshal,
   13.59 +	const KeHashMarshal *val_marshal,
   13.60 +	ke_allocator_t *nodeAlloc,
   13.61 +	bool keep_free_list)
   13.62 +{
   13.63 +	KeHashTable *table;
   13.64 +
   13.65 +	if (bits >= 27)
   13.66 +	{
   13.67 +		bits = 26;
   13.68 +	}
   13.69 +	else if (bits < 4)
   13.70 +	{
   13.71 +		bits = 4;
   13.72 +	}
   13.73 +
   13.74 +	/* Validate marshals. */
   13.75 +	if ((key_marshal->bytes != 0
   13.76 +		 && key_marshal->ctor == NULL)
   13.77 +		|| (val_marshal->bytes != 0
   13.78 +			&& val_marshal->ctor == NULL))
   13.79 +	{
   13.80 +		return NULL;
   13.81 +	}
   13.82 +
   13.83 +	table = new KeHashTable;
   13.84 +	table->key_gen = key_gen;
   13.85 +	table->key_m = *key_marshal;
   13.86 +	table->val_m = *val_marshal;
   13.87 +	table->num_entries = 0;
   13.88 +	table->shift = bits;
   13.89 +	table->node_alloc = nodeAlloc == NULL ? &s_DefHashAllocator : nodeAlloc;
   13.90 +	table->num_buckets = (1 << bits);
   13.91 +	table->grow_limit = (uint32_t)(0.9f * table->num_buckets);
   13.92 +	table->keep_free_list = keep_free_list;
   13.93 +	table->free_list = NULL;
   13.94 +	table->buckets = (KeHashNode **)malloc(sizeof(KeHashNode *) * table->num_buckets);
   13.95 +	memset(table->buckets, 0, sizeof(KeHashNode *) * table->num_buckets);
   13.96 +
   13.97 +	table->key_offs = sizeof(KeHashNode);
   13.98 +	if (table->key_m.bytes != 0 && table->key_m.bytes % 8 != 0)
   13.99 +	{
  13.100 +		table->key_m.bytes += 8;
  13.101 +		table->key_m.bytes -= (table->key_m.bytes % 8);
  13.102 +	}
  13.103 +	
  13.104 +	table->val_offs = table->key_offs + table->key_m.bytes;
  13.105 +	table->node_size = table->val_offs + table->val_m.bytes;
  13.106 +
  13.107 +	return table;
  13.108 +}
  13.109 +
  13.110 +#define KE_GET_BUCKET(tbl, hsh) (&(tbl)->buckets[((hsh) * 0x9E3779B9) >> (tbl)->shift])
  13.111 +
  13.112 +KeHashNode **ke_HashInternalFind(KeHashTable *table, uint32_t key_hash, const void *key)
  13.113 +{
  13.114 +	KeHashNode *node;
  13.115 +	KeHashNode **bucket;
  13.116 +
  13.117 +	bucket = KE_GET_BUCKET(table, key_hash);
  13.118 +
  13.119 +	/* :TODO: move to the front once found? */
  13.120 +
  13.121 +	while ((node = *bucket) != NULL)
  13.122 +	{
  13.123 +		if (node->key_hash == key_hash
  13.124 +			&& ((table->key_m.cmp != NULL && table->key_m.cmp(node->key, key))
  13.125 +				 || node->key == key))
  13.126 +		{
  13.127 +			return bucket;
  13.128 +		}
  13.129 +		bucket = &node->next;
  13.130 +	}
  13.131 +
  13.132 +	return bucket;
  13.133 +}
  13.134 +
  13.135 +void ke_ResizeHashTable(KeHashTable *table, uint32_t new_shift)
  13.136 +{
  13.137 +	uint32_t entries;
  13.138 +	KeHashNode *next;
  13.139 +	KeHashNode *node;
  13.140 +	KeHashNode **rbucket;
  13.141 +	KeHashNode **old_buckets;
  13.142 +	uint32_t old_num_buckets;
  13.143 +
  13.144 +	/* Save old data */
  13.145 +	old_num_buckets = table->num_buckets;
  13.146 +	old_buckets = table->buckets;
  13.147 +	entries = table->num_entries;
  13.148 +
  13.149 +	/* Save new data */
  13.150 +	table->num_buckets = (1 << new_shift);
  13.151 +	table->shift = new_shift;
  13.152 +	table->grow_limit = (uint32_t)(0.9f * table->num_buckets);
  13.153 +
  13.154 +	table->buckets = (KeHashNode **)malloc(sizeof(KeHashNode *) * table->num_buckets);
  13.155 +	memset(table->buckets, 0, sizeof(KeHashNode *) * table->num_buckets);
  13.156 +
  13.157 +	/* For each old bucket... */
  13.158 +	for (uint32_t i = 0;
  13.159 +		 i < old_num_buckets && entries != 0;
  13.160 +		 i++)
  13.161 +	{
  13.162 +		node = old_buckets[i];
  13.163 +		/* Get each item in its list... */
  13.164 +		while (node != NULL)
  13.165 +		{
  13.166 +			next = node->next;
  13.167 +			
  13.168 +			/* Find the new replacement bucket it needs to go in. */
  13.169 +			rbucket = KE_GET_BUCKET(table, node->key_hash);
  13.170 +
  13.171 +			/* Link this node to the next node in the new bucket. */
  13.172 +			if (*rbucket == NULL)
  13.173 +			{
  13.174 +				node->next = NULL;
  13.175 +			}
  13.176 +			else
  13.177 +			{
  13.178 +				node->next = *rbucket;
  13.179 +			}
  13.180 +
  13.181 +			/* Add us to the front of that bucket's list. */
  13.182 +			*rbucket = node;
  13.183 +
  13.184 +			node = next;
  13.185 +		}
  13.186 +	}
  13.187 +
  13.188 +	free(old_buckets);
  13.189 +}
  13.190 +
  13.191 +void Knight::KE_AddToHashTable(KeHashTable *table, const void *key, void *val)
  13.192 +{
  13.193 +	KeHashNode *node;
  13.194 +	uint32_t key_hash;
  13.195 +	KeHashNode **bucket;
  13.196 +
  13.197 +	key_hash = table->key_gen(key);
  13.198 +	bucket = ke_HashInternalFind(table, key_hash, key);
  13.199 +
  13.200 +	if ((node = *bucket) != NULL)
  13.201 +	{
  13.202 +		/* Already in the table */
  13.203 +		if ((table->val_m.cmp != NULL && table->val_m.cmp(node->value, val))
  13.204 +			 || node->value == val)
  13.205 +		{
  13.206 +			return;
  13.207 +		}
  13.208 +
  13.209 +		/* Destroy old value if it's set. */
  13.210 +		if (node->value != NULL && table->val_m.dtor != NULL)
  13.211 +		{
  13.212 +			table->val_m.dtor(node->value);
  13.213 +		}
  13.214 +		
  13.215 +		/* Construct or set the new value. */
  13.216 +		if (table->val_m.bytes != 0)
  13.217 +		{
  13.218 +			table->val_m.ctor(node->value, val);
  13.219 +		}
  13.220 +		else
  13.221 +		{
  13.222 +			node->value = val;
  13.223 +		}
  13.224 +
  13.225 +		return;
  13.226 +	}
  13.227 +
  13.228 +	/* If we're overloaded, we may need to resize. 
  13.229 +	 * Right now, we do this if we hit a .9 entry:buckets ratio.
  13.230 +	 */
  13.231 +	if (table->num_entries >= table->grow_limit)
  13.232 +	{
  13.233 +		ke_ResizeHashTable(table, table->shift << 1);
  13.234 +		bucket = ke_HashInternalFind(table, key_hash, key);
  13.235 +	}
  13.236 +
  13.237 +	if (table->free_list != NULL)
  13.238 +	{
  13.239 +		node = table->free_list;
  13.240 +		table->free_list = node->next;
  13.241 +	}
  13.242 +	else
  13.243 +	{
  13.244 +		node = (KeHashNode *)table->node_alloc->alloc(table->node_alloc, table->node_size);
  13.245 +	}
  13.246 +	
  13.247 +	if (table->key_m.bytes == 0)
  13.248 +	{
  13.249 +		node->key = key;
  13.250 +	}
  13.251 +	else
  13.252 +	{
  13.253 +		node->key = (char *)node + table->key_offs;
  13.254 +		table->key_m.ctor((void *)node->key, key);
  13.255 +	}
  13.256 +
  13.257 +	if (table->val_m.bytes == 0)
  13.258 +	{
  13.259 +		node->value = val;
  13.260 +	}
  13.261 +	else
  13.262 +	{
  13.263 +		node->value = (char *)node + table->val_offs;
  13.264 +		table->val_m.ctor(node->value, val);
  13.265 +	}
  13.266 +
  13.267 +	node->next = *bucket;
  13.268 +	node->key_hash = key_hash;
  13.269 +	*bucket = node;
  13.270 +}
  13.271 +
  13.272 +inline void ke_CleanUpHashNode(KeHashTable *table, KeHashNode *node)
  13.273 +{
  13.274 +	/* Destroy old value if it's set. */
  13.275 +	if (node->value != NULL && table->val_m.dtor != NULL)
  13.276 +	{
  13.277 +		table->val_m.dtor(node->value);
  13.278 +	}
  13.279 +
  13.280 +	/* Destroy the key. */
  13.281 +	if (table->key_m.dtor != NULL)
  13.282 +	{
  13.283 +		table->key_m.dtor(node->key);
  13.284 +	}
  13.285 +
  13.286 +	/* Deallocate us as appropriate. */
  13.287 +	if (table->keep_free_list)
  13.288 +	{
  13.289 +		node->next = table->free_list;
  13.290 +		table->free_list = node;
  13.291 +	}
  13.292 +	else
  13.293 +	{
  13.294 +		table->node_alloc->dealloc(table->node_alloc, node);
  13.295 +	}
  13.296 +}
  13.297 +
  13.298 +void Knight::KE_RemoveFromHashTable(KeHashTable *table, const void *key)
  13.299 +{
  13.300 +	KeHashNode *node;
  13.301 +	uint32_t key_hash;
  13.302 +	KeHashNode **bucket;
  13.303 +
  13.304 +	key_hash = table->key_gen(key);
  13.305 +	bucket = ke_HashInternalFind(table, key_hash, key);
  13.306 +
  13.307 +	if ((node = *bucket) == NULL)
  13.308 +	{
  13.309 +		return;
  13.310 +	}
  13.311 +
  13.312 +	/* Link the bucket to its next (removing us). */
  13.313 +	*bucket = node->next;
  13.314 +
  13.315 +	ke_CleanUpHashNode(table, node);
  13.316 +}
  13.317 +
  13.318 +bool Knight::KE_FindInHashTable(KeHashTable *table, const void *key, void **value)
  13.319 +{
  13.320 +	KeHashNode *node;
  13.321 +	uint32_t key_hash;
  13.322 +	KeHashNode **bucket;
  13.323 +
  13.324 +	key_hash = table->key_gen(key);
  13.325 +	bucket = ke_HashInternalFind(table, key_hash, key);
  13.326 +
  13.327 +	if ((node = *bucket) == NULL)
  13.328 +	{
  13.329 +		return false;
  13.330 +	}
  13.331 +
  13.332 +	if (value != NULL)
  13.333 +	{
  13.334 +		*value = node->value;
  13.335 +	}
  13.336 +
  13.337 +	return true;
  13.338 +}
  13.339 +
  13.340 +void Knight::KE_DestroyHashTable(KeHashTable *table)
  13.341 +{
  13.342 +	KeHashNode *node, *next;
  13.343 +
  13.344 +	/* Turn off this caching! */
  13.345 +	table->keep_free_list = false;
  13.346 +
  13.347 +	/* Find entries in buckets that need to be freed. */
  13.348 +	for (uint32_t i = 0; i < table->num_buckets; i++)
  13.349 +	{
  13.350 +		node = table->buckets[i];
  13.351 +
  13.352 +		while (node != NULL)
  13.353 +		{
  13.354 +			next = node->next;
  13.355 +			ke_CleanUpHashNode(table, node);
  13.356 +			node = next;
  13.357 +		}
  13.358 +	}
  13.359 +
  13.360 +	/* Free the free list */
  13.361 +	while (table->free_list != NULL)
  13.362 +	{
  13.363 +		next = table->free_list->next;
  13.364 +		ke_CleanUpHashNode(table, table->free_list);
  13.365 +		table->free_list = next;
  13.366 +	}
  13.367 +
  13.368 +	/* Destroy everything now. */
  13.369 +	free(table->buckets);
  13.370 +	delete table;
  13.371 +}
  13.372 +
  13.373 +void Knight::KE_ClearHashTable(KeHashTable *table)
  13.374 +{
  13.375 +	KeHashNode *node, *next;
  13.376 +
  13.377 +	/* Free every entry in the table. */
  13.378 +	for (uint32_t i = 0; i < table->num_buckets; i++)
  13.379 +	{
  13.380 +		node = table->buckets[i];
  13.381 +
  13.382 +		while (node != NULL)
  13.383 +		{
  13.384 +			next = node->next;
  13.385 +			ke_CleanUpHashNode(table, node);
  13.386 +			node = next;
  13.387 +		}
  13.388 +	}
  13.389 +}
  13.390 +
  13.391 +#if defined _MSC_VER && (defined _M_IX86 || defined _M_AMD64 || defined _M_X64)
  13.392 +#pragma intrinsic(_rotl)
  13.393 +#endif
  13.394 +
  13.395 +uint32_t Knight::KE_HashString(const void *str)
  13.396 +{
  13.397 +	uint32_t h;
  13.398 +	const unsigned char *us;
  13.399 +
  13.400 +	h = 0;
  13.401 +
  13.402 +	for (us = (const unsigned char *)str; *us != 0; us++)
  13.403 +	{
  13.404 +#if defined _MSC_VER && (defined _M_IX86 || defined _M_AMD64 || defined _M_X64)
  13.405 +		h = _rotl(h, 4) ^ *us;
  13.406 +#else
  13.407 +		h = ((h << 4) | (h >> 28)) ^ *us;
  13.408 +#endif
  13.409 +	}
  13.410 +
  13.411 +	return h;
  13.412 +}
    14.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    14.2 +++ b/knight/shared/KeHashTable.h	Fri Aug 15 05:22:26 2008 +0000
    14.3 @@ -0,0 +1,128 @@
    14.4 +#ifndef _INCLUDE_KNIGHT_KE_HASHTABLE_H_
    14.5 +#define _INCLUDE_KNIGHT_KE_HASHTABLE_H_
    14.6 +
    14.7 +#include <KeStdTypes.h>
    14.8 +#include <KnightAllocator.h>
    14.9 +
   14.10 +namespace Knight
   14.11 +{
   14.12 +	class KeHashTable;
   14.13 +
   14.14 +	/**
   14.15 +	 * @brief Must generate a hash function given a key.
   14.16 +	 *
   14.17 +	 * @param key				Pointer to the key.
   14.18 +	 * @return					Hash value.
   14.19 +	 */
   14.20 +	typedef uint32_t (*KeHashGenerator)(const void *key);
   14.21 +
   14.22 +	/**
   14.23 +	 * @brief Must compare two values.
   14.24 +	 *
   14.25 +	 * @param val1				First value.
   14.26 +	 * @param val2				Second value.
   14.27 +	 * @return					True if equal, false if not.
   14.28 +	 */
   14.29 +	typedef bool (*KeHashComparator)(const void *val1, const void *val2);
   14.30 +
   14.31 +	/**
   14.32 +	 * @brief Must call the destructor of the given data, and free if necessary.
   14.33 +	 *
   14.34 +	 * @param val				Pointer to data.
   14.35 +	 */
   14.36 +	typedef void (*KeHashDestructor)(const void *val);
   14.37 +
   14.38 +	/**
   14.39 +	 * @brief Must transfer the contents of an object from the source to the destination.
   14.40 +	 *
   14.41 +	 * @param dest				Destination address.
   14.42 +	 * @param source			Source address.
   14.43 +	 */
   14.44 +	typedef void (*KeHashCopyCtor)(void *dest, const void *source);
   14.45 +
   14.46 +	/**
   14.47 +	 * @brief Contains information about how to process keys and values in a hash table.
   14.48 +	 */
   14.49 +	struct KeHashMarshal
   14.50 +	{
   14.51 +		size_t bytes;				/**< Bytes of storage needed (0 to use pointers). */
   14.52 +		KeHashComparator cmp;		/**< Comparator (if NULL, void * comparison used) */
   14.53 +		KeHashDestructor dtor;		/**< Optional function for performing dtor cleanup. */
   14.54 +		KeHashCopyCtor ctor;		/**< If bytes != 0, must be a valid function 
   14.55 +										 (ignored otherwise). */
   14.56 +	};
   14.57 +
   14.58 +	/**
   14.59 +	 * @brief Creates a new hash table structure.
   14.60 +	 *
   14.61 +	 * @param bits				Dictates starting number of buckets as a power of two.
   14.62 +	 *							Pass 0 for the default (which is 4).
   14.63 +	 * @param key_gen			Key generation function.
   14.64 +	 * @param key_marshal		Structure detailing how to marshal keys.
   14.65 +	 * @param vak_marshal		Structure detailing how to marshal values.
   14.66 +	 * @param nodeAlloc			Node allocator (can be NULL for malloc/free).
   14.67 +	 * @param keep_free_list	True to keep a free list of nodes, false otherwise.
   14.68 +	 * @return					New hash table container.
   14.69 +	 */
   14.70 +	extern KeHashTable *KE_CreateHashTable(
   14.71 +		uint32_t bits,
   14.72 +		KeHashGenerator key_gen,
   14.73 +		const KeHashMarshal *key_marshal,
   14.74 +		const KeHashMarshal *val_marshal,
   14.75 +		ke_allocator_t *nodeAlloc,
   14.76 +		bool keep_free_list
   14.77 +		);
   14.78 +
   14.79 +	/**
   14.80 +	 * @brief Destroys a hash table.
   14.81 +	 *
   14.82 +	 * @param table				Hash table.
   14.83 +	 */
   14.84 +	extern void KE_DestroyHashTable(KeHashTable *table);
   14.85 +
   14.86 +	/**
   14.87 +	 * @brief Adds a key/value to the hash table.  If the pair already exists, the old value 
   14.88 +	 * is overwritten (calling any destructors as necessary).
   14.89 +	 *
   14.90 +	 * @param table				Hash table.
   14.91 +	 * @param key				Key pointer.
   14.92 +	 * @param val				Value pointer.
   14.93 +	 */
   14.94 +	extern void KE_AddToHashTable(KeHashTable *table, const void *key, void *val);
   14.95 +
   14.96 +	/**
   14.97 +	 * @brief Removes a key entry from the hash table.
   14.98 +	 *
   14.99 +	 * @param table				Hash table.
  14.100 +	 * @param key				Key pointer.
  14.101 +	 */
  14.102 +	extern void KE_RemoveFromHashTable(KeHashTable *table, const void *key);
  14.103 +
  14.104 +	/**
  14.105 +	 * @brief Finds an entry in the hash table.
  14.106 +	 *
  14.107 +	 * @param table				Hash table.
  14.108 +	 * @param key				Key pointer.
  14.109 +	 * @param value				Pointer to store the value (optional).
  14.110 +	 * @return					On success, true is returned and value is filled if given.
  14.111 +	 *							On failure, false is failed and outputs are undefined.
  14.112 +	 */
  14.113 +	extern bool KE_FindInHashTable(KeHashTable *table, const void *key, void **value);
  14.114 +
  14.115 +	/**
  14.116 +	 * @brief Clears all entries in the hash table (caching free entries when possible).
  14.117 +	 *
  14.118 +	 * @param table				Hash table.
  14.119 +	 */
  14.120 +	extern void KE_ClearHashTable(KeHashTable *table);
  14.121 +
  14.122 +	/**
  14.123 +	 * @brief Generic function for hasing strings.
  14.124 +	 *
  14.125 +	 * @param str				Key string.
  14.126 +	 * @return					Hash value.
  14.127 +	 */
  14.128 +	extern uint32_t KE_HashString(const void *str);
  14.129 +}
  14.130 +
  14.131 +#endif //_INCLUDE_KNIGHT_KE_HASHTABLE_H_
    15.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    15.2 +++ b/knight/shared/KeLinking.h	Fri Aug 15 05:22:26 2008 +0000
    15.3 @@ -0,0 +1,12 @@
    15.4 +#ifndef _INCLUDE_KNIGHT_LINKING_H_
    15.5 +#define _INCLUDE_KNIGHT_LINKING_H_
    15.6 +
    15.7 +#if defined KE_LINK_IMPORT
    15.8 +#error "Not yet supported"
    15.9 +#elif defined KE_LINK_EXPORT
   15.10 +#error "Not yet supported"
   15.11 +#else
   15.12 +#define KE_LINK
   15.13 +#endif
   15.14 +
   15.15 +#endif //_INCLUDE_KNIGHT_LINKING_H_
    16.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    16.2 +++ b/knight/shared/KeLumpAllocator.cpp	Fri Aug 15 05:22:26 2008 +0000
    16.3 @@ -0,0 +1,258 @@
    16.4 +#include "KePlatform.h"
    16.5 +#include <KeLumpAllocator.h>
    16.6 +#include <KeVector.h>
    16.7 +
    16.8 +using namespace Knight;
    16.9 +
   16.10 +/**
   16.11 + * :TODO: don't make this part of the page, because touching it means 
   16.12 + * dirtying a page.  Instead, we should have a separate linked list.
   16.13 + * Maybe that linked list itself could be marshalled from one page.
   16.14 + */
   16.15 +struct KeLumpRegion
   16.16 +{
   16.17 +	char *base;
   16.18 +	char *cur;
   16.19 +	size_t size;
   16.20 +	size_t avail;
   16.21 +	KeLumpRegion *next;
   16.22 +	KeLumpRegion *prev;
   16.23 +};
   16.24 +
   16.25 +class KeLumpAllocator
   16.26 +{
   16.27 +public:
   16.28 +	KeLumpAllocator() : m_pUsableRegions(NULL), m_pUnusableRegions(NULL)
   16.29 +	{
   16.30 +		m_DefLumpSize = 65536;
   16.31 +
   16.32 +#if defined KE_PLATFORM_WINDOWS
   16.33 +		SYSTEM_INFO info;
   16.34 +
   16.35 +		GetSystemInfo(&info);
   16.36 +		if (info.dwAllocationGranularity > m_DefLumpSize)
   16.37 +		{
   16.38 +			m_DefLumpSize = info.dwAllocationGranularity;
   16.39 +		}
   16.40 +#endif
   16.41 +	}
   16.42 +
   16.43 +	~KeLumpAllocator()
   16.44 +	{
   16.45 +		FreeRegionChain(m_pUsableRegions);
   16.46 +		FreeRegionChain(m_pUnusableRegions);
   16.47 +	}
   16.48 +
   16.49 +	void Reset()
   16.50 +	{
   16.51 +		KeLumpRegion *region;
   16.52 +
   16.53 +		/* Find the tail of the usable regions. */
   16.54 +		region = m_pUsableRegions;
   16.55 +		while (region != NULL)
   16.56 +		{
   16.57 +			if (region->next == NULL)
   16.58 +			{
   16.59 +				break;
   16.60 +			}
   16.61 +		}
   16.62 +
   16.63 +		/* Link the unusable chain into the usable chain. */
   16.64 +		if (region == NULL)
   16.65 +		{
   16.66 +			m_pUsableRegions = m_pUnusableRegions;
   16.67 +		}
   16.68 +		else
   16.69 +		{
   16.70 +			region->next = m_pUnusableRegions;
   16.71 +			m_pUnusableRegions->prev = region;
   16.72 +		}
   16.73 +		m_pUnusableRegions = NULL;
   16.74 +
   16.75 +		region = m_pUsableRegions;
   16.76 +		while (region != NULL)
   16.77 +		{
   16.78 +			region->avail = region->size;
   16.79 +			region->cur = region->base;
   16.80 +			region = region->next;
   16.81 +		}
   16.82 +	}
   16.83 +
   16.84 +	void FreeRegionChain(KeLumpRegion *region)
   16.85 +	{
   16.86 +		KeLumpRegion *next;
   16.87 +
   16.88 +		while (region != NULL)
   16.89 +		{
   16.90 +			next = region->next;
   16.91 +			
   16.92 +#if defined KE_PLATFORM_WINDOWS
   16.93 +			VirtualFree(region, 0, MEM_RELEASE);
   16.94 +#endif
   16.95 +			region = next;
   16.96 +		}
   16.97 +	}
   16.98 +
   16.99 +	void *Alloc(size_t size)
  16.100 +	{
  16.101 +		char *blob;
  16.102 +		KeLumpRegion *region;
  16.103 +
  16.104 +		if (size % 8 != 0)
  16.105 +		{
  16.106 +			size += 8;
  16.107 +			size -= size % 8;
  16.108 +		}
  16.109 +
  16.110 +		region = FindRegionForSize(size);
  16.111 +
  16.112 +		blob = region->cur;
  16.113 +		region->avail -= size;
  16.114 +		region->cur += size;
  16.115 +
  16.116 +		/** 
  16.117 +		 * Technically we could make one last small allocation, but 
  16.118 +		 * this edge case is not worth the extra work.
  16.119 +		 */
  16.120 +		if (region->avail < 8)
  16.121 +		{
  16.122 +			/* Unlink us from the usable list */
  16.123 +			if (region == m_pUsableRegions)
  16.124 +			{
  16.125 +				m_pUsableRegions = m_pUsableRegions->next;
  16.126 +				m_pUsableRegions->prev = NULL;
  16.127 +			}
  16.128 +			else
  16.129 +			{
  16.130 +				region->prev->next = region->next;
  16.131 +				if (region->next != NULL)
  16.132 +				{
  16.133 +					region->next->prev = region->prev;
  16.134 +				}
  16.135 +			}
  16.136 +
  16.137 +			/* Link us into the unusable list */
  16.138 +			region->prev = NULL;
  16.139 +			region->next = m_pUnusableRegions;
  16.140 +
  16.141 +			if (m_pUnusableRegions != NULL)
  16.142 +			{
  16.143 +				m_pUnusableRegions->prev = region;
  16.144 +			}
  16.145 +
  16.146 +			m_pUnusableRegions = region;
  16.147 +		}
  16.148 +
  16.149 +		return blob;
  16.150 +	}
  16.151 +
  16.152 +private:
  16.153 +	KeLumpRegion *FindRegionForSize(size_t size)
  16.154 +	{
  16.155 +		char *base;
  16.156 +		KeLumpRegion *region;
  16.157 +		size_t size_of_region;
  16.158 +
  16.159 +		/**
  16.160 +		 * :TODO: replace this with a priority queue or something 
  16.161 +		 * that's actually fast.  Even worse is we dirty pages by 
  16.162 +		 * doing this.  Ouch!
  16.163 +		 */
  16.164 +		region = m_pUsableRegions;
  16.165 +		while (region != NULL)
  16.166 +		{
  16.167 +			if (region->avail >= size)
  16.168 +			{
  16.169 +				return region;
  16.170 +			}
  16.171 +			region = region->next;
  16.172 +		}
  16.173 +
  16.174 +		/* Make sure regions end at 8-byte alignment. */
  16.175 +		size_of_region = sizeof(KeLumpRegion);
  16.176 +		if (size_of_region % 8 != 0)
  16.177 +		{
  16.178 +			size_of_region += 8;
  16.179 +			size_of_region -= size_of_region % 8;
  16.180 +		}
  16.181 +
  16.182 +		/* If the size is too big, fix that. */
  16.183 +		if (size > m_DefLumpSize - size_of_region)
  16.184 +		{
  16.185 +			size += m_DefLumpSize;
  16.186 +			size -= size % m_DefLumpSize;
  16.187 +		}
  16.188 +		else
  16.189 +		{
  16.190 +			size = m_DefLumpSize;
  16.191 +		}
  16.192 +
  16.193 +#if defined KE_PLATFORM_WINDOWS
  16.194 +		base = (char *)VirtualAlloc(
  16.195 +			NULL,
  16.196 +			m_DefLumpSize,
  16.197 +			MEM_COMMIT|MEM_RESERVE,
  16.198 +			PAGE_READWRITE);
  16.199 +#endif
  16.200 +
  16.201 +		/* Initialize the region */
  16.202 +		region = (KeLumpRegion *)base;
  16.203 +		region->base = &base[size_of_region];
  16.204 +		region->size = size - size_of_region;
  16.205 +		region->cur = region->base;
  16.206 +		region->avail = region->size;
  16.207 +		region->prev = NULL;
  16.208 +		region->next = m_pUsableRegions;
  16.209 +
  16.210 +		if (m_pUsableRegions != NULL)
  16.211 +		{
  16.212 +			m_pUsableRegions->prev = region;
  16.213 +		}
  16.214 +
  16.215 +		m_pUsableRegions = region;
  16.216 +
  16.217 +		return region;
  16.218 +	}
  16.219 +
  16.220 +private:
  16.221 +	KeLumpRegion *m_pUsableRegions;
  16.222 +	KeLumpRegion *m_pUnusableRegions;
  16.223 +	size_t m_DefLumpSize;
  16.224 +};
  16.225 +
  16.226 +inline KeLumpAllocator *ke_LumpFromAllocator(ke_allocator_t *arena)
  16.227 +{
  16.228 +	return (KeLumpAllocator *)arena->user;
  16.229 +}
  16.230 +
  16.231 +void *ke_LumpAlloc(ke_allocator_t *arena, size_t size)
  16.232 +{
  16.233 +	return ke_LumpFromAllocator(arena)->Alloc(size);
  16.234 +}
  16.235 +
  16.236 +void ke_LumpFree(ke_allocator_t *arena, void *ptr)
  16.237 +{
  16.238 +}
  16.239 +
  16.240 +ke_allocator_t * KE_LINK Knight::KE_CreateLumpAllocator()
  16.241 +{
  16.242 +	ke_allocator_t *alloc;
  16.243 +
  16.244 +	alloc = new ke_allocator_t;
  16.245 +	alloc->alloc = ke_LumpAlloc;
  16.246 +	alloc->dealloc = ke_LumpFree;
  16.247 +	alloc->user = new KeLumpAllocator();
  16.248 +
  16.249 +	return alloc;
  16.250 +}
  16.251 +
  16.252 +void KE_LINK Knight::KE_DestroyLumpAllocator(ke_allocator_t *alloc)
  16.253 +{
  16.254 +	delete ke_LumpFromAllocator(alloc);
  16.255 +	delete alloc;
  16.256 +}
  16.257 +
  16.258 +void KE_LINK Knight::KE_ResetLumpAllocator(ke_allocator_t *alloc)
  16.259 +{
  16.260 +	ke_LumpFromAllocator(alloc)->Reset();
  16.261 +}
    17.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    17.2 +++ b/knight/shared/KeLumpAllocator.h	Fri Aug 15 05:22:26 2008 +0000
    17.3 @@ -0,0 +1,36 @@
    17.4 +#ifndef _INCLUDE_KNIGHT_KE_LUMP_ALLOCATOR_H_
    17.5 +#define _INCLUDE_KNIGHT_KE_LUMP_ALLOCATOR_H_
    17.6 +
    17.7 +#include <KeLinking.h>
    17.8 +#include <KnightAllocator.h>
    17.9 +
   17.10 +namespace Knight
   17.11 +{
   17.12 +	/**
   17.13 +	 * @brief Creates a new lump allocator.
   17.14 +	 *
   17.15 +	 * The lump allocator is intended for cases where there are many allocations 
   17.16 +	 * and none need to be freed.  There is memory wastage, and the lump allocator 
   17.17 +	 * is typically thrown away after use.
   17.18 +	 *
   17.19 +	 * @return			New lump allocator.
   17.20 +	 */
   17.21 +	extern ke_allocator_t * KE_CreateLumpAllocator();
   17.22 +
   17.23 +	/**
   17.24 +	 * @brief Destroys a lump allocator, freeing all of its resources.
   17.25 +	 *
   17.26 +	 * @param lump		Lump allocator.
   17.27 +	 */
   17.28 +	extern void KE_DestroyLumpAllocator(ke_allocator_t *alloc);
   17.29 +
   17.30 +	/**
   17.31 +	 * @brief Clears a lump allocator, so its memory can be re-used from 
   17.32 +	 * the start.
   17.33 +	 *
   17.34 +	 * @param lump		Lump allocator.
   17.35 +	 */
   17.36 +	extern void KE_ResetLumpAllocator(ke_allocator_t *alloc);
   17.37 +}
   17.38 +
   17.39 +#endif //_INCLUDE_KNIGHT_KE_LUMP_ALLOCATOR_H_
    18.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    18.2 +++ b/knight/shared/KePageAllocator.cpp	Fri Aug 15 05:22:26 2008 +0000
    18.3 @@ -0,0 +1,148 @@
    18.4 +#include "KePageAllocator.h"
    18.5 +
    18.6 +using namespace Knight;
    18.7 +
    18.8 +struct PageInfo
    18.9 +{
   18.10 +	PageInfo *next;
   18.11 +	void *base;
   18.12 +};
   18.13 +
   18.14 +class Knight::KePageAllocator
   18.15 +{
   18.16 +public:
   18.17 +	size_t page_size;
   18.18 +	size_t page_granularity;
   18.19 +	PageInfo *free_pages;
   18.20 +	PageInfo *page_blocks;
   18.21 +};
   18.22 +
   18.23 +static void *ke_LumpPageAlloc(KePageAllocator *alloc)
   18.24 +{
   18.25 +	void *base;
   18.26 +	char *page;
   18.27 +	PageInfo *lump;
   18.28 +	size_t pagesInBlock;
   18.29 +
   18.30 +#if defined KE_PLATFORM_WINDOWS
   18.31 +	base = VirtualAlloc(
   18.32 +		NULL,
   18.33 +		alloc->page_granularity,
   18.34 +		MEM_COMMIT|MEM_RESERVE,
   18.35 +		PAGE_READWRITE);
   18.36 +#elif defined KE_PLATFORM_POSIX
   18.37 +	base = valloc(alloc->page_granularity);
   18.38 +#else 
   18.39 +#error "Unsupported platform"
   18.40 +#endif
   18.41 +
   18.42 +	if (base == NULL)
   18.43 +	{
   18.44 +		return NULL;
   18.45 +	}
   18.46 +
   18.47 +	lump = new PageInfo;
   18.48 +	lump->base = base;
   18.49 +	lump->next = alloc->page_blocks;
   18.50 +	alloc->page_blocks = lump->next;
   18.51 +
   18.52 +	page = (char *)base + alloc->page_size;
   18.53 +	pagesInBlock = alloc->page_granularity / alloc->page_size;
   18.54 +
   18.55 +	for (size_t i = 1; i < pagesInBlock; i++)
   18.56 +	{
   18.57 +		lump = new PageInfo;
   18.58 +		lump->base = page;
   18.59 +		lump->next = alloc->free_pages;
   18.60 +		alloc->free_pages = lump;
   18.61 +		page += alloc->page_size;
   18.62 +	}
   18.63 +
   18.64 +	return base;
   18.65 +}
   18.66 +
   18.67 +KePageAllocator *Knight::KE_CreatePageAllocator()
   18.68 +{
   18.69 +	KePageAllocator *alloc;
   18.70 +
   18.71 +	alloc = new KePageAllocator;
   18.72 +	
   18.73 +#if defined KE_PLATFORM_WINDOWS
   18.74 +	SYSTEM_INFO info;
   18.75 +	
   18.76 +	GetSystemInfo(&info);
   18.77 +	alloc->page_size = info.dwPageSize;
   18.78 +	alloc->page_granularity = info.dwAllocationGranularity;
   18.79 +#elif defined KE_PLATFORM_POSIX
   18.80 +	alloc->page_size = sysconf(_SC_PAGESIZE);
   18.81 +	alloc->page_granularity = alloc->page_size * 16;
   18.82 +#else 
   18.83 +#error "Unsupported platform"
   18.84 +#endif
   18.85 +
   18.86 +	alloc->free_pages = NULL;
   18.87 +	alloc->page_blocks = NULL;
   18.88 +
   18.89 +	return alloc;
   18.90 +}
   18.91 +
   18.92 +void Knight::KE_DestroyPageAllocator(KePageAllocator *alloc)
   18.93 +{
   18.94 +	PageInfo *info, *next;
   18.95 +
   18.96 +	info = alloc->page_blocks;
   18.97 +	while (info != NULL)
   18.98 +	{
   18.99 +		next = info->next;
  18.100 +#if defined KE_PLATFORM_WINDOWS
  18.101 +		VirtualFree(info->base, 0, MEM_RELEASE);
  18.102 +#elif defined KE_PLATFORM_WINDOWS
  18.103 +		free(info->base);
  18.104 +#else 
  18.105 +#error "Unsupported platform"
  18.106 +#endif
  18.107 +		delete info;
  18.108 +		next = info;
  18.109 +	}
  18.110 +
  18.111 +	info = alloc->free_pages;
  18.112 +	while (info != NULL)
  18.113 +	{
  18.114 +		next = info->next;
  18.115 +		delete info;
  18.116 +		info = next;
  18.117 +	}
  18.118 +}
  18.119 +
  18.120 +void *Knight::KE_PageAlloc(KePageAllocator *alloc)
  18.121 +{
  18.122 +	if (alloc->free_pages != NULL)
  18.123 +	{
  18.124 +		void *base;
  18.125 +		PageInfo *info;
  18.126 +
  18.127 +		info = alloc->free_pages;
  18.128 +		alloc->free_pages = info->next;
  18.129 +		base = info->base;
  18.130 +		delete info;
  18.131 +
  18.132 +		return base;
  18.133 +	}
  18.134 +
  18.135 +	return ke_LumpPageAlloc(alloc);
  18.136 +}
  18.137 +
  18.138 +void Knight::KE_PageFree(KePageAllocator *alloc, void *page)
  18.139 +{
  18.140 +	PageInfo *info;
  18.141 +
  18.142 +	info = new PageInfo;
  18.143 +	info->base = page;
  18.144 +	info->next = alloc->free_pages;
  18.145 +	alloc->free_pages = info->next;
  18.146 +}
  18.147 +
  18.148 +size_t Knight::KE_PageSize(KePageAllocator *alloc)
  18.149 +{
  18.150 +	return alloc->page_size;
  18.151 +}
    19.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    19.2 +++ b/knight/shared/KePageAllocator.h	Fri Aug 15 05:22:26 2008 +0000
    19.3 @@ -0,0 +1,49 @@
    19.4 +#ifndef _INCLUDE_KNIGHT_KE_PAGE_ALLOCATOR_H_
    19.5 +#define _INCLUDE_KNIGHT_KE_PAGE_ALLOCATOR_H_
    19.6 +
    19.7 +#include <KeStdTypes.h>
    19.8 +
    19.9 +namespace Knight
   19.10 +{
   19.11 +	class KePageAllocator;
   19.12 +
   19.13 +	/**
   19.14 +	 * @brief Creates a page allocator.
   19.15 +	 *
   19.16 +	 * @return				New page allocator.
   19.17 +	 */
   19.18 +	extern KePageAllocator *KE_CreatePageAllocator();
   19.19 +
   19.20 +	/**
   19.21 +	 * @brief Destroys a page allocator, freeing all live pages it owns.
   19.22 +	 *
   19.23 +	 * @param				Page allocator.
   19.24 +	 */
   19.25 +	extern void KE_DestroyPageAllocator(KePageAllocator *alloc);
   19.26 +
   19.27 +	/**
   19.28 +	 * @brief Allocates a page of memory.
   19.29 +	 *
   19.30 +	 * @param alloc			Page allocator.
   19.31 +	 * @return				Page of memory.
   19.32 +	 */
   19.33 +	extern void *KE_PageAlloc(KePageAllocator *alloc);
   19.34 +
   19.35 +	/**
   19.36 +	* @brief Frees a page of memory.
   19.37 +	*
   19.38 +	* @param alloc			Page allocator.
   19.39 +	* @param page			Page of memory.
   19.40 +	*/
   19.41 +	extern void KE_PageFree(KePageAllocator *alloc, void *page);
   19.42 +
   19.43 +	/**
   19.44 +	* @brief Returns the size of a page.
   19.45 +	*
   19.46 +	* @param alloc			Page allocator.
   19.47 +	* @return				Page size.
   19.48 +	*/
   19.49 +	extern size_t KE_PageSize(KePageAllocator *alloc);
   19.50 +}
   19.51 +
   19.52 +#endif //_INCLUDE_KNIGHT_KE_PAGE_ALLOCATOR_H_
    20.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    20.2 +++ b/knight/shared/KePlatform.h	Fri Aug 15 05:22:26 2008 +0000
    20.3 @@ -0,0 +1,27 @@
    20.4 +#ifndef _INCLUDE_KNIGHT_KE_PLATFORM_H_
    20.5 +#define _INCLUDE_KNIGHT_KE_PLATFORM_H_
    20.6 +
    20.7 +#if defined WIN32
    20.8 +
    20.9 +#define KE_PLATFORM_WINDOWS
   20.10 +#define WINDOWS_LEAN_AND_MEAN
   20.11 +#include <windows.h>
   20.12 +#include <malloc.h>
   20.13 +
   20.14 +#if !defined alloca
   20.15 +#define alloca _alloca
   20.16 +#endif
   20.17 +
   20.18 +#else
   20.19 +
   20.20 +#define KE_PLATFORM_POSIX
   20.21 +
   20.22 +#if defined linux
   20.23 +#define KE_PLATFORM_LINUX
   20.24 +#else
   20.25 +#error "TODO"
   20.26 +#endif
   20.27 +
   20.28 +#endif
   20.29 +
   20.30 +#endif //_INCLUDE_KNIGHT_KE_PLATFORM_H_
    21.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    21.2 +++ b/knight/shared/KeSectorStack.h	Fri Aug 15 05:22:26 2008 +0000
    21.3 @@ -0,0 +1,162 @@
    21.4 +#ifndef _INCLUDE_KNIGHT_KE_SECTOR_STACK_H_
    21.5 +#define _INCLUDE_KNIGHT_KE_SECTOR_STACK_H_
    21.6 +
    21.7 +#include <KnightAllocator.h>
    21.8 +#include <KeVector.h>
    21.9 +
   21.10 +namespace Knight
   21.11 +{
   21.12 +	template <class T>
   21.13 +	class KeSectorStack
   21.14 +	{
   21.15 +	public:
   21.16 +		static const size_t DEFAULT_SECTOR_SIZE = 64;
   21.17 +
   21.18 +		KeSectorStack() : m_SectorSize(DEFAULT_SECTOR_SIZE), m_UsedSize(0), m_MaxUsedSize(0)
   21.19 +		{
   21.20 +			m_pAlloc = NULL;
   21.21 +		}
   21.22 +
   21.23 +		KeSectorStack(size_t sectorSize) : m_SectorSize(sectorSize), m_UsedSize(0), m_MaxUsedSize(0)
   21.24 +		{
   21.25 +			m_pAlloc = NULL;
   21.26 +		}
   21.27 +
   21.28 +		KeSectorStack(size_t sectorSize, ke_allocator_t *alloc) : 
   21.29 +			m_SectorSize(sectorSize), m_UsedSize(0), m_pAlloc(alloc), m_MaxUsedSize(0)
   21.30 +		{
   21.31 +		}
   21.32 +
   21.33 +		~KeSectorStack()
   21.34 +		{
   21.35 +			clear();
   21.36 +		}
   21.37 +
   21.38 +		void clear()
   21.39 +		{
   21.40 +			T *sector;
   21.41 +			size_t last_sector;
   21.42 +			size_t last_sector_item;
   21.43 +
   21.44 +			if (m_MaxUsedSize == 0)
   21.45 +			{
   21.46 +				return;
   21.47 +			}
   21.48 +
   21.49 +			last_sector = (m_MaxUsedSize - 1) / m_SectorSize;
   21.50 +			last_sector_item = (m_MaxUsedSize - 1) % m_SectorSize;
   21.51 +
   21.52 +			for (size_t i = 0; i < last_sector; i++)
   21.53 +			{
   21.54 +				sector = m_Sectors[i];
   21.55 +
   21.56 +				for (size_t j = 0; j < m_SectorSize; j++)
   21.57 +				{
   21.58 +					sector[j].~T();
   21.59 +				}
   21.60 +			}
   21.61 +
   21.62 +			sector = m_Sectors[last_sector];
   21.63 +			for (size_t i = 0; i <= last_sector_item; i++)
   21.64 +			{
   21.65 +				sector[i].~T();
   21.66 +			}
   21.67 +
   21.68 +			clear_no_dtors();
   21.69 +		}
   21.70 +
   21.71 +		void clear_no_dtors()
   21.72 +		{
   21.73 +			for (size_t i = 0; i < m_Sectors.size(); i++)
   21.74 +			{
   21.75 +				free_sector(m_Sectors[i]);
   21.76 +			}
   21.77 +
   21.78 +			m_Sectors.clear();
   21.79 +		}
   21.80 +
   21.81 +		bool empty()
   21.82 +		{
   21.83 +			return (m_UsedSize == 0) ? true : false;
   21.84 +		}
   21.85 +
   21.86 +		void push(const T & val)
   21.87 +		{
   21.88 +			if ((m_UsedSize / m_SectorSize) >= m_Sectors.size())
   21.89 +			{
   21.90 +				/* Create a new sector */
   21.91 +				T * sector;
   21.92 +				
   21.93 +				if (m_pAlloc == NULL)
   21.94 +				{
   21.95 +					sector = (T *)malloc(sizeof(T) * m_SectorSize);
   21.96 +				}
   21.97 +				else 
   21.98 +				{
   21.99 +					sector = (T *)m_pAlloc->alloc(m_pAlloc, sizeof(T) * m_SectorSize);
  21.100 +				}
  21.101 +
  21.102 +				m_Sectors.push_back(sector);
  21.103 +			}
  21.104 +
  21.105 +			at(m_UsedSize) = val;
  21.106 +
  21.107 +			m_UsedSize++;
  21.108 +
  21.109 +			/* Keep track of the maximum used size so we can defer the 
  21.110 +			 * massive destruction job until the end.
  21.111 +			 */
  21.112 +			if (m_UsedSize > m_MaxUsedSize)
  21.113 +			{
  21.114 +				m_MaxUsedSize = m_UsedSize;
  21.115 +			}
  21.116 +		}
  21.117 +
  21.118 +		void pop()
  21.119 +		{
  21.120 +			m_UsedSize--;
  21.121 +		}
  21.122 +
  21.123 +		void pop_all()
  21.124 +		{
  21.125 +			m_UsedSize = 0;
  21.126 +		}
  21.127 +
  21.128 +		T & front()
  21.129 +		{
  21.130 +			return at(m_UsedSize - 1);
  21.131 +		}
  21.132 +
  21.133 +		size_t size()
  21.134 +		{
  21.135 +			return m_UsedSize;
  21.136 +		}
  21.137 +
  21.138 +	private:
  21.139 +		T & at(size_t x)
  21.140 +		{
  21.141 +			return m_Sectors[x / m_SectorSize][x % m_SectorSize];
  21.142 +		}
  21.143 +
  21.144 +		void free_sector(T * sector)
  21.145 +		{
  21.146 +			if (m_pAlloc == NULL)
  21.147 +			{
  21.148 +				free(sector);
  21.149 +			}
  21.150 +			else if (m_pAlloc->dealloc != NULL)
  21.151 +			{
  21.152 +				m_pAlloc->dealloc(m_pAlloc, sector);
  21.153 +			}
  21.154 +		}
  21.155 +
  21.156 +	private:
  21.157 +		KeVector<T *> m_Sectors;
  21.158 +		size_t m_SectorSize;
  21.159 +		size_t m_UsedSize;
  21.160 +		ke_allocator_t *m_pAlloc;
  21.161 +		size_t m_MaxUsedSize;
  21.162 +	};
  21.163 +}
  21.164 +
  21.165 +#endif //_INCLUDE_KNIGHT_KE_SECTOR_STACK_H_
    22.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    22.2 +++ b/knight/shared/KeStdTypes.h	Fri Aug 15 05:22:26 2008 +0000
    22.3 @@ -0,0 +1,24 @@
    22.4 +#ifndef _INCLUDE_KNIGHT_KE_STANDARD_TYPES_H_
    22.5 +#define _INCLUDE_KNIGHT_KE_STANDARD_TYPES_H_
    22.6 +
    22.7 +#include <KePlatform.h>
    22.8 +#include <stddef.h>
    22.9 +
   22.10 +#if defined KE_PLATFORM_WINDOWS
   22.11 +
   22.12 +typedef __int8 int8_t;
   22.13 +typedef unsigned __int8 uint8_t;
   22.14 +typedef __int16 int16_t;
   22.15 +typedef unsigned __int16 uint16_t;
   22.16 +typedef __int32 int32_t;
   22.17 +typedef unsigned __int32 uint32_t;
   22.18 +typedef __int64 int64_t;
   22.19 +typedef unsigned __int64 uint64_t;
   22.20 +
   22.21 +#else
   22.22 +
   22.23 +#include <stdint.h>
   22.24 +
   22.25 +#endif
   22.26 +
   22.27 +#endif //_INCLUDE_KNIGHT_KE_STANDARD_TYPES_H_
    23.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    23.2 +++ b/knight/shared/KeVector.h	Fri Aug 15 05:22:26 2008 +0000
    23.3 @@ -0,0 +1,158 @@
    23.4 +#ifndef _INCLUDE_KNIGHT_KE_VECTOR_H_
    23.5 +#define _INCLUDE_KNIGHT_KE_VECTOR_H_
    23.6 +
    23.7 +#include <new>
    23.8 +
    23.9 +namespace Knight
   23.10 +{
   23.11 +	template <class T>
   23.12 +	class KeVector
   23.13 +	{
   23.14 +	public:
   23.15 +		KeVector<T>() : m_Data(NULL), m_Size(0), m_CurrentUsedSize(0)
   23.16 +		{
   23.17 +		}
   23.18 +
   23.19 +		KeVector<T>(const KeVector<T> & other)
   23.20 +		{
   23.21 +			m_Size = other.m_CurrentUsedSize;
   23.22 +			m_CurrentUsedSize = other.m_CurrentUsedSize;
   23.23 +
   23.24 +			if (m_Size > 0)
   23.25 +			{
   23.26 +				m_Data = new T[other.m_CurrentUsedSize];
   23.27 +
   23.28 +				for (size_t i = 0; i < m_Size; i++)
   23.29 +				{
   23.30 +					m_Data[i] = other.m_Data[i];
   23.31 +				}
   23.32 +			}
   23.33 +			else
   23.34 +			{
   23.35 +				m_Data = NULL;
   23.36 +			}
   23.37 +		}
   23.38 +
   23.39 +		~KeVector<T>()
   23.40 +		{
   23.41 +			clear();
   23.42 +		}
   23.43 +
   23.44 +		KeVector & operator =(const KeVector<T> & other)
   23.45 +		{
   23.46 +			clear();
   23.47 +
   23.48 +			if (other.m_CurrentUsedSize)
   23.49 +			{
   23.50 +				m_Data = new T[other.m_CurrentUsedSize];
   23.51 +				m_Size = other.m_CurrentUsedSize;
   23.52 +				m_CurrentUsedSize = other.m_CurrentUsedSize;
   23.53 +
   23.54 +				for (size_t i = 0; i < m_Size; i++)
   23.55 +				{
   23.56 +					m_Data[i] = other.m_Data[i];
   23.57 +				}
   23.58 +			}
   23.59 +		}
   23.60 +
   23.61 +		size_t size() const
   23.62 +		{
   23.63 +			return m_CurrentUsedSize;
   23.64 +		}
   23.65 +
   23.66 +		void push_back(const T & elem)
   23.67 +		{
   23.68 +			GrowIfNeeded(1);
   23.69 +
   23.70 +			new (&m_Data[m_CurrentUsedSize]) T(elem);
   23.71 +
   23.72 +			m_CurrentUsedSize++;
   23.73 +		}
   23.74 +
   23.75 +		void pop_back(const T & elem)
   23.76 +		{
   23.77 +			if (m_CurrentUsedSize == 0)
   23.78 +			{
   23.79 +				return;
   23.80 +			}
   23.81 +
   23.82 +			m_CurrentUsedSize--;
   23.83 +			m_Data[m_CurrentUsedSize].~T();
   23.84 +		}
   23.85 +
   23.86 +		bool is_empty()
   23.87 +		{
   23.88 +			return (m_CurrentUsedSize == 0);
   23.89 +		}
   23.90 +
   23.91 +		T & operator [](size_t pos)
   23.92 +		{
   23.93 +			return m_Data[pos];
   23.94 +		}
   23.95 +
   23.96 +		const T & operator [](size_t pos) const
   23.97 +		{
   23.98 +			return m_Data[pos];
   23.99 +		}
  23.100 +
  23.101 +		void clear()
  23.102 +		{
  23.103 +			for (size_t i = 0; i < m_CurrentUsedSize; i++)
  23.104 +			{
  23.105 +				m_Data[i].~T();
  23.106 +			}
  23.107 +
  23.108 +			free(m_Data);
  23.109 +			
  23.110 +			m_Data = NULL;
  23.111 +			m_Size = 0;
  23.112 +			m_CurrentUsedSize = 0;
  23.113 +		}
  23.114 +	private:
  23.115 +		void Grow(size_t amount)
  23.116 +		{
  23.117 +			T *new_data;
  23.118 +			size_t new_size;
  23.119 +
  23.120 +			if (m_Size == 0)
  23.121 +			{
  23.122 +				new_size = 8;
  23.123 +			}
  23.124 +			else
  23.125 +			{
  23.126 +				new_size = m_Size * 2;
  23.127 +			}
  23.128 +
  23.129 +			while (m_CurrentUsedSize + amount > new_size)
  23.130 +			{
  23.131 +				new_size *= 2;
  23.132 +			}
  23.133 +
  23.134 +			new_data = (T *)malloc(sizeof(T) * new_size);
  23.135 +
  23.136 +			for (size_t i = 0; i < m_CurrentUsedSize; i++)
  23.137 +			{
  23.138 +				new (&new_data[i]) T(m_Data[i]);
  23.139 +				m_Data[i].~T();
  23.140 +			}
  23.141 +
  23.142 +			free(m_Data);
  23.143 +			m_Data = new_data;
  23.144 +			m_Size = new_size;
  23.145 +		}
  23.146 +
  23.147 +		void GrowIfNeeded(size_t amount)
  23.148 +		{
  23.149 +			if (m_CurrentUsedSize + amount >= m_Size)
  23.150 +			{
  23.151 +				Grow(amount);
  23.152 +			}
  23.153 +		}
  23.154 +	private:
  23.155 +		T *m_Data;
  23.156 +		size_t m_Size;
  23.157 +		size_t m_CurrentUsedSize;
  23.158 +	};
  23.159 +}
  23.160 +
  23.161 +#endif //_INCLUDE_KNIGHT_KE_VECTOR_H_
    24.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    24.2 +++ b/knight/shared/KnightAllocator.h	Fri Aug 15 05:22:26 2008 +0000
    24.3 @@ -0,0 +1,37 @@
    24.4 +#ifndef _INCLUDE_KNIGHT_ALLOCATOR_H_
    24.5 +#define _INCLUDE_KNIGHT_ALLOCATOR_H_
    24.6 +
    24.7 +#include <stddef.h>
    24.8 +#include <stdlib.h>
    24.9 +
   24.10 +struct ke_allocator_s;
   24.11 +typedef struct ke_allocator_s ke_allocator_t;
   24.12 +
   24.13 +typedef void *(*KEFN_ALLOCATOR)(ke_allocator_t *, size_t);
   24.14 +typedef void (*KEFN_DEALLOCATOR)(ke_allocator_t *, void *);
   24.15 +
   24.16 +struct ke_allocator_s
   24.17 +{
   24.18 +	KEFN_ALLOCATOR alloc;
   24.19 +	KEFN_DEALLOCATOR dealloc;
   24.20 +	void *user;
   24.21 +};
   24.22 +
   24.23 +inline void *operator new(size_t size, ke_allocator_t *alloc)
   24.24 +{
   24.25 +	return alloc->alloc(alloc, size);
   24.26 +}
   24.27 +
   24.28 +inline void *operator new [](size_t size, ke_allocator_t *alloc)
   24.29 +{
   24.30 +	return alloc->alloc(alloc, size);
   24.31 +}
   24.32 +
   24.33 +template <typename T>
   24.34 +void ke_destroy(ke_allocator_t *alloc, T * data)
   24.35 +{
   24.36 +	data->~T();
   24.37 +	alloc->dealloc(alloc, data);
   24.38 +}
   24.39 +
   24.40 +#endif //_INCLUDE_KNIGHT_ALLOCATOR_H_
    25.1 --- a/public/IPluginSys.h	Sun Aug 10 05:39:25 2008 +0000
    25.2 +++ b/public/IPluginSys.h	Fri Aug 15 05:22:26 2008 +0000
    25.3 @@ -296,7 +296,7 @@
    25.4  		 * @brief Attempts to load a plugin.
    25.5  		 *
    25.6  		 * @param path		Path and filename of plugin, relative to plugins folder.
    25.7 -		 * @param debug		Whether or not to default the plugin into debug mode.
    25.8 +		 * @param debug		Deprecated, must be false.
    25.9  		 * @param type		Lifetime of the plugin.
   25.10  		 * @param error		Buffer to hold any error message.
   25.11  		 * @param maxlength	Maximum length of error message buffer.
    26.1 --- a/public/jit/jit_helpers.h	Sun Aug 10 05:39:25 2008 +0000
    26.2 +++ b/public/jit/jit_helpers.h	Fri Aug 15 05:22:26 2008 +0000
    26.3 @@ -65,6 +65,10 @@
    26.4  		inptr++;
    26.5  		return val;
    26.6  	}
    26.7 +	inline cell_t peek_cell()
    26.8 +	{
    26.9 +		return *inptr;
   26.10 +	}
   26.11  	inline cell_t *read_cellptr()
   26.12  	{
   26.13  		cell_t *val = *(cell_t **)(inptr);
    27.1 --- a/public/jit/x86/x86_macros.h	Sun Aug 10 05:39:25 2008 +0000
    27.2 +++ b/public/jit/x86/x86_macros.h	Fri Aug 15 05:22:26 2008 +0000
    27.3 @@ -998,6 +998,38 @@
    27.4  	jit->write_int32(val);
    27.5  }
    27.6  
    27.7 +inline void IA32_Mov_Rm_Imm32_SIB(JitWriter *jit, 
    27.8 +								  jit_uint8_t dest, 
    27.9 +								  jit_int32_t val, 
   27.10 +								  jit_int32_t disp,
   27.11 +								  jit_uint8_t index,
   27.12 +								  jit_uint8_t scale)
   27.13 +{
   27.14 +	jit->write_ubyte(IA32_MOV_RM_IMM32);
   27.15 +
   27.16 +	if (disp >= SCHAR_MIN && disp <= SCHAR_MAX)
   27.17 +	{
   27.18 +		jit->write_ubyte(ia32_modrm(MOD_DISP8, 0, REG_SIB));
   27.19 +	}
   27.20 +	else
   27.21 +	{
   27.22 +		jit->write_ubyte(ia32_modrm(MOD_DISP32, 0, REG_SIB));
   27.23 +	}
   27.24 +
   27.25 +	jit->write_ubyte(ia32_sib(scale, index, dest));
   27.26 +
   27.27 +	if (disp >= SCHAR_MIN && disp <= SCHAR_MAX)
   27.28 +	{
   27.29 +		jit->write_byte((jit_int8_t)disp);
   27.30 +	}
   27.31 +	else
   27.32 +	{
   27.33 +		jit->write_int32(disp);
   27.34 +	}
   27.35 +
   27.36 +	jit->write_int32(val);
   27.37 +}
   27.38 +
   27.39  inline void IA32_Mov_RmEBP_Imm32_Disp_Reg(JitWriter *jit, 
   27.40  								jit_uint8_t dest_base, 
   27.41  								jit_uint8_t dest_index, 
   27.42 @@ -1347,24 +1379,39 @@
   27.43  	jit->outptr = oldptr;
   27.44  }
   27.45  
   27.46 -/* For writing and auto-calculating an absolute target */
   27.47 -inline void IA32_Jump_Imm32_Abs(JitWriter *jit, jitoffs_t target)
   27.48 +/* For writing and auto-calculating a relative target */
   27.49 +inline void IA32_Jump_Imm32_Rel(JitWriter *jit, jitoffs_t target)
   27.50  {
   27.51 -	/* :TODO: this should work, but does it? */
   27.52  	jit->write_ubyte(IA32_JMP_IMM32);
   27.53  	IA32_Write_Jump32(jit, jit->get_outputpos(), target);
   27.54  	jit->outptr += 4;
   27.55  }
   27.56  
   27.57 -inline void IA32_Jump_Cond_Imm32_Abs(JitWriter *jit, jit_uint8_t cond, jitoffs_t target)
   27.58 +/* For writing and auto-calculating an absolute target */
   27.59 +inline void IA32_Jump_Imm32_Abs(JitWriter *jit, void *target)
   27.60  {
   27.61 -	/* :TODO: this should work, but does it? */
   27.62 +	jitoffs_t jmp;
   27.63 +
   27.64 +	jmp = IA32_Jump_Imm32(jit, 0);
   27.65 +	IA32_Write_Jump32_Abs(jit, jmp, target);
   27.66 +}
   27.67 +
   27.68 +inline void IA32_Jump_Cond_Imm32_Rel(JitWriter *jit, jit_uint8_t cond, jitoffs_t target)
   27.69 +{
   27.70  	jit->write_ubyte(IA32_JCC_IMM32_1);
   27.71  	jit->write_ubyte(IA32_JCC_IMM32_2+cond);
   27.72  	IA32_Write_Jump32(jit, jit->get_outputpos(), target);
   27.73  	jit->outptr += 4;
   27.74  }
   27.75  
   27.76 +inline void IA32_Jump_Cond_Imm32_Abs(JitWriter *jit, jit_uint8_t cond, void *target)
   27.77 +{
   27.78 +	jit->write_ubyte(IA32_JCC_IMM32_1);
   27.79 +	jit->write_ubyte(IA32_JCC_IMM32_2+cond);
   27.80 +	IA32_Write_Jump32_Abs(jit, jit->get_outputpos(), target);
   27.81 +	jit->outptr += 4;
   27.82 +}
   27.83 +
   27.84  inline void IA32_Send_Jump8_Here(JitWriter *jit, jitoffs_t jmp)
   27.85  {
   27.86  	jitoffs_t curptr = jit->get_outputpos();
    28.1 --- a/public/sourcepawn/sp_file_headers.h	Sun Aug 10 05:39:25 2008 +0000
    28.2 +++ b/public/sourcepawn/sp_file_headers.h	Fri Aug 15 05:22:26 2008 +0000
    28.3 @@ -98,6 +98,9 @@
    28.4  
    28.5  #define SP_FLAG_DEBUG	(1<<0)		/**< Debug information is present in the file */
    28.6  
    28.7 +#define SP_CODEVERS_JIT1       9    /**< Code version for JIT1 */
    28.8 +#define SP_CODEVERS_JIT2      10    /**< Code version for JIT2 */    
    28.9 +
   28.10  /**
   28.11   * @brief File-encoded format of the ".code" section.
   28.12   */
    29.1 --- a/public/sourcepawn/sp_vm_api.h	Sun Aug 10 05:39:25 2008 +0000
    29.2 +++ b/public/sourcepawn/sp_vm_api.h	Fri Aug 15 05:22:26 2008 +0000
    29.3 @@ -42,7 +42,7 @@
    29.4  
    29.5  /** SourcePawn Engine API Version */
    29.6  #define SOURCEPAWN_ENGINE_API_VERSION	4
    29.7 -#define SOURCEPAWN_ENGINE2_API_VERSION	1
    29.8 +#define SOURCEPAWN_ENGINE2_API_VERSION	2
    29.9  
   29.10  #if !defined SOURCEMOD_BUILD
   29.11  #define SOURCEMOD_BUILD
   29.12 @@ -955,7 +955,21 @@
   29.13  	class IDebugListener
   29.14  	{
   29.15  	public:
   29.16 +		/**
   29.17 +		 * @brief Invoked on a context execution error.
   29.18 +		 * 
   29.19 +		 * @param ctx		Context.
   29.20 +		 * @param error		Object holding error information and a backtrace.
   29.21 +		 */
   29.22  		virtual void OnContextExecuteError(IPluginContext *ctx, IContextTrace *error) =0;
   29.23 +
   29.24 +		/**
   29.25 +		 * @brief Called on debug spew.
   29.26 +		 *
   29.27 +		 * @param msg		Message text.
   29.28 +		 * @param fmt		Message formatting arguments (printf-style).
   29.29 +		 */
   29.30 +		virtual void OnDebugSpew(const char *msg, ...) =0;
   29.31  	};
   29.32  
   29.33  	/**
   29.34 @@ -1225,6 +1239,19 @@
   29.35  		 * @return			Error string, or NULL if not found.
   29.36  		 */
   29.37  		virtual const char *GetErrorString(int err) =0;
   29.38 +
   29.39 +		/**
   29.40 +		 * @brief Initializes the SourcePawn engine.
   29.41 +		 *
   29.42 +		 * @return			True on success, false if failed.
   29.43 +		 */
   29.44 +		virtual bool Initialize() =0;
   29.45 +		
   29.46 +		/**
   29.47 +		 * @brief Shuts down the SourcePawn engine.  Only needs to be called if 
   29.48 +		 * Initialize() succeeded.
   29.49 +		 */
   29.50 +		virtual void Shutdown() =0;
   29.51  	};
   29.52  };
   29.53  
    30.1 --- a/public/sourcepawn/sp_vm_types.h	Sun Aug 10 05:39:25 2008 +0000
    30.2 +++ b/public/sourcepawn/sp_vm_types.h	Fri Aug 15 05:22:26 2008 +0000
    30.3 @@ -83,6 +83,8 @@
    30.4  #define SP_ERROR_NATIVE					23	/**< Error originates from a native */
    30.5  #define SP_ERROR_NOT_RUNNABLE			24	/**< Function or plugin is not runnable */
    30.6  #define SP_ERROR_ABORTED				25	/**< Function call was aborted */
    30.7 +#define SP_ERROR_CODE_TOO_OLD			26	/**< Code is too old for this VM */
    30.8 +#define SP_ERROR_CODE_TOO_NEW			27	/**< Code is too new for this VM */
    30.9  //Hey you! Update the string table if you add to the end of me! */
   30.10  
   30.11  /**********************************************
   30.12 @@ -201,7 +203,4 @@
   30.13  	sp_fdbg_symbol_t	*sym;	/**< Pointer to original symbol */
   30.14  } sp_debug_symbol_t;
   30.15  
   30.16 -//#define SPFLAG_PLUGIN_DEBUG		(1<<0)		/**< plugin is in debug mode */
   30.17 -//#define SPFLAG_PLUGIN_PAUSED	(1<<1)		/**< plugin is "paused" (blocked from executing) */
   30.18 -
   30.19  #endif //_INCLUDE_SOURCEPAWN_VM_TYPES_H
    31.1 --- a/sourcepawn/jit/BaseRuntime.cpp	Sun Aug 10 05:39:25 2008 +0000
    31.2 +++ b/sourcepawn/jit/BaseRuntime.cpp	Fri Aug 15 05:22:26 2008 +0000
    31.3 @@ -1,6 +1,7 @@
    31.4  #include <stdio.h>
    31.5  #include <stdlib.h>
    31.6  #include <string.h>
    31.7 +#include <assert.h>
    31.8  #include "BaseRuntime.h"
    31.9  #include "sp_vm_engine.h"
   31.10  #include "x86/jit_x86.h"
   31.11 @@ -9,61 +10,225 @@
   31.12  
   31.13  using namespace SourcePawn;
   31.14  
   31.15 -int GlobalDebugBreak(BaseContext *ctx, uint32_t frm, uint32_t cip)
   31.16 +BaseRuntime::BaseRuntime() : m_Debug(&m_plugin), m_pPlugin(&m_plugin), m_pCtx(NULL), 
   31.17 +m_PubFuncs(NULL), m_PubJitFuncs(NULL), m_pCo(NULL), m_CompSerial(0)
   31.18  {
   31.19 -	g_engine1.RunTracer(ctx, frm, cip);
   31.20 -
   31.21 -	return SP_ERROR_NONE;
   31.22 -}
   31.23 -
   31.24 -BaseRuntime::BaseRuntime(sp_plugin_t *pl) : m_Debug(pl), m_pPlugin(pl)
   31.25 -{
   31.26 -	m_pCtx = new BaseContext(this);
   31.27 +	memset(&m_plugin, 0, sizeof(m_plugin));
   31.28  
   31.29 -	if (m_pPlugin->info.publics_num > 0)
   31.30 -	{
   31.31 -		m_PubFuncs = new CFunction *[m_pPlugin->info.publics_num];
   31.32 -		memset(m_PubFuncs, 0, sizeof(CFunction *) * m_pPlugin->info.publics_num);
   31.33 -	}
   31.34 -	else
   31.35 -	{
   31.36 -		m_PubFuncs = NULL;
   31.37 -	}
   31.38 -
   31.39 -	m_pPlugin->dbreak = GlobalDebugBreak;
   31.40 -	m_pPlugin->profiler = g_engine2.GetProfiler();
   31.41 +	m_FuncCache = NULL;
   31.42 +	m_MaxFuncs = 0;
   31.43 +	m_NumFuncs = 0;
   31.44  }
   31.45  
   31.46  BaseRuntime::~BaseRuntime()
   31.47  {
   31.48 -	for (uint32_t i = 0; i < m_pPlugin->info.publics_num; i++)
   31.49 +	for (uint32_t i = 0; i < m_pPlugin->num_publics; i++)
   31.50  	{
   31.51  		delete m_PubFuncs[i];
   31.52  		m_PubFuncs[i] = NULL;
   31.53  	}
   31.54  	delete [] m_PubFuncs;
   31.55 +	delete [] m_PubJitFuncs;
   31.56  
   31.57 -	ClearCompile();
   31.58 +	for (unsigned int i = 0; i < m_NumFuncs; i++)
   31.59 +	{
   31.60 +		delete m_FuncCache[i];
   31.61 +	}
   31.62 +	free(m_FuncCache);
   31.63 +
   31.64 +	delete m_pCtx;
   31.65 +	delete m_pCo;
   31.66  
   31.67  	free(m_pPlugin->base);
   31.68  	delete [] m_pPlugin->memory;
   31.69 +	delete [] m_pPlugin->publics;
   31.70 +	delete [] m_pPlugin->pubvars;
   31.71  	delete [] m_pPlugin->natives;
   31.72 -	delete m_pPlugin;
   31.73 +	free(m_pPlugin->name);
   31.74 +}
   31.75 +
   31.76 +static cell_t InvalidNative(IPluginContext *pCtx, const cell_t *params)
   31.77 +{
   31.78 +	return pCtx->ThrowNativeErrorEx(SP_ERROR_INVALID_NATIVE, "Invalid native");
   31.79  }
   31.80  
   31.81 -void BaseRuntime::ClearCompile()
   31.82 +int BaseRuntime::CreateFromMemory(sp_file_hdr_t *hdr, uint8_t *base)
   31.83  {
   31.84 -	g_Jit1.FreeContextVars(m_pCtx->GetCtx());
   31.85 -	g_Jit1.FreePluginVars(m_pPlugin);
   31.86 +	int set_err;
   31.87 +	char *nameptr;
   31.88 +	uint8_t sectnum = 0;
   31.89 +	sp_plugin_t *plugin = m_pPlugin;
   31.90 +	sp_file_section_t *secptr = (sp_file_section_t *)(base + sizeof(sp_file_hdr_t));
   31.91 +
   31.92 +	memset(plugin, 0, sizeof(sp_plugin_t));
   31.93 +
   31.94 +	plugin->base = base;
   31.95 +	plugin->base_size = hdr->imagesize;
   31.96 +	set_err = SP_ERROR_NONE;
   31.97 +
   31.98 +	/* We have to read the name section first */
   31.99 +	for (sectnum = 0; sectnum < hdr->sections; sectnum++)
  31.100 +	{
  31.101 +		nameptr = (char *)(base + hdr->stringtab + secptr[sectnum].nameoffs);
  31.102 +		if (strcmp(nameptr, ".names") == 0)
  31.103 +		{
  31.104 +			plugin->stringbase = (const char *)(base + secptr[sectnum].dataoffs);
  31.105 +			break;
  31.106 +		}
  31.107 +	}
  31.108 +
  31.109 +	sectnum = 0;
  31.110 +
  31.111 +	/* Now read the rest of the sections */
  31.112 +	while (sectnum < hdr->sections)
  31.113 +	{
  31.114 +		nameptr = (char *)(base + hdr->stringtab + secptr->nameoffs);
  31.115 +
  31.116 +		if (!(plugin->pcode) && !strcmp(nameptr, ".code"))
  31.117 +		{
  31.118 +			sp_file_code_t *cod = (sp_file_code_t *)(base + secptr->dataoffs);
  31.119 +
  31.120 +			if (cod->codeversion < SP_CODEVERS_JIT1)
  31.121 +			{
  31.122 +				return SP_ERROR_CODE_TOO_OLD;
  31.123 +			}
  31.124 +			else if (cod->codeversion > SP_CODEVERS_JIT2)
  31.125 +			{
  31.126 +				return SP_ERROR_CODE_TOO_NEW;
  31.127 +			}
  31.128 +
  31.129 +			plugin->pcode = base + secptr->dataoffs + cod->code;
  31.130 +			plugin->pcode_size = cod->codesize;
  31.131 +			plugin->flags = cod->flags;
  31.132 +			plugin->pcode_version = cod->codeversion;
  31.133 +		}
  31.134 +		else if (!(plugin->data) && !strcmp(nameptr, ".data"))
  31.135 +		{
  31.136 +			sp_file_data_t *dat = (sp_file_data_t *)(base + secptr->dataoffs);
  31.137 +			plugin->data = base + secptr->dataoffs + dat->data;
  31.138 +			plugin->data_size = dat->datasize;
  31.139 +			plugin->mem_size = dat->memsize;
  31.140 +			plugin->memory = new uint8_t[plugin->mem_size];
  31.141 +			memcpy(plugin->memory, plugin->data, plugin->data_size);
  31.142 +		}
  31.143 +		else if ((plugin->publics == NULL) && !strcmp(nameptr, ".publics"))
  31.144 +		{
  31.145 +			sp_file_publics_t *publics;
  31.146 +
  31.147 +			publics = (sp_file_publics_t *)(base + secptr->dataoffs);
  31.148 +			plugin->num_publics = secptr->size / sizeof(sp_file_publics_t);
  31.149 +
  31.150 +			if (plugin->num_publics > 0)
  31.151 +			{
  31.152 +				plugin->publics = new sp_public_t[plugin->num_publics];
  31.153 +
  31.154 +				for (uint32_t i = 0; i < plugin->num_publics; i++)
  31.155 +				{
  31.156 +					plugin->publics[i].code_offs = publics[i].address;
  31.157 +					plugin->publics[i].funcid = (i << 1) | 1;
  31.158 +					plugin->publics[i].name = plugin->stringbase + publics[i].name;
  31.159 +				}
  31.160 +			}
  31.161 +		}
  31.162 +		else if ((plugin->pubvars == NULL) && !strcmp(nameptr, ".pubvars"))
  31.163 +		{
  31.164 +			sp_file_pubvars_t *pubvars;
  31.165 +
  31.166 +			pubvars = (sp_file_pubvars_t *)(base + secptr->dataoffs);
  31.167 +			plugin->num_pubvars = secptr->size / sizeof(sp_file_pubvars_t);
  31.168 +
  31.169 +			if (plugin->num_pubvars > 0)
  31.170 +			{
  31.171 +				plugin->pubvars = new sp_pubvar_t[plugin->num_pubvars];
  31.172 +
  31.173 +				for (uint32_t i = 0; i < plugin->num_pubvars; i++)
  31.174 +				{
  31.175 +					plugin->pubvars[i].name = plugin->stringbase + pubvars[i].name;
  31.176 +					plugin->pubvars[i].offs = (cell_t *)(plugin->memory + pubvars[i].address);
  31.177 +				}
  31.178 +			}
  31.179 +		}
  31.180 +		else if ((plugin->natives == NULL) && !strcmp(nameptr, ".natives"))
  31.181 +		{
  31.182 +			sp_file_natives_t *natives;
  31.183 +
  31.184 +			natives = (sp_file_natives_t *)(base + secptr->dataoffs);
  31.185 +			plugin->num_natives = secptr->size / sizeof(sp_file_natives_t);
  31.186 +
  31.187 +			if (plugin->num_natives > 0)
  31.188 +			{
  31.189 +				plugin->natives = new sp_native_t[plugin->num_natives];
  31.190 +
  31.191 +				for (uint32_t i = 0; i < plugin->num_natives; i++)
  31.192 +				{
  31.193 +					plugin->natives[i].flags = 0;
  31.194 +					plugin->natives[i].pfn = InvalidNative;
  31.195 +					plugin->natives[i].status = SP_NATIVE_UNBOUND;
  31.196 +					plugin->natives[i].user = NULL;
  31.197 +					plugin->natives[i].name = plugin->stringbase + natives[i].name;
  31.198 +				}
  31.199 +			}
  31.200 +		}
  31.201 +		else if (!(plugin->debug.files) && !strcmp(nameptr, ".dbg.files"))
  31.202 +		{
  31.203 +			plugin->debug.files = (sp_fdbg_file_t *)(base + secptr->dataoffs);
  31.204 +		}
  31.205 +		else if (!(plugin->debug.lines) && !strcmp(nameptr, ".dbg.lines"))
  31.206 +		{
  31.207 +			plugin->debug.lines = (sp_fdbg_line_t *)(base + secptr->dataoffs);
  31.208 +		}
  31.209 +		else if (!(plugin->debug.symbols) && !strcmp(nameptr, ".dbg.symbols"))
  31.210 +		{
  31.211 +			plugin->debug.symbols = (sp_fdbg_symbol_t *)(base + secptr->dataoffs);
  31.212 +		}
  31.213 +		else if (!(plugin->debug.lines_num) && !strcmp(nameptr, ".dbg.info"))
  31.214 +		{
  31.215 +			sp_fdbg_info_t *inf = (sp_fdbg_info_t *)(base + secptr->dataoffs);
  31.216 +			plugin->debug.files_num = inf->num_files;
  31.217 +			plugin->debug.lines_num = inf->num_lines;
  31.218 +			plugin->debug.syms_num = inf->num_syms;
  31.219 +		}
  31.220 +		else if (!(plugin->debug.stringbase) && !strcmp(nameptr, ".dbg.strings"))
  31.221 +		{
  31.222 +			plugin->debug.stringbase = (const char *)(base + secptr->dataoffs);
  31.223 +		}
  31.224 +
  31.225 +		secptr++;
  31.226 +		sectnum++;
  31.227 +	}
  31.228 +
  31.229 +	if (plugin->pcode == NULL || plugin->data == NULL)
  31.230 +	{
  31.231 +		return SP_ERROR_FILE_FORMAT;
  31.232 +	}
  31.233 +
  31.234 +	if ((plugin->flags & SP_FLAG_DEBUG) && (!(plugin->debug.files) || !(plugin->debug.lines) || !(plugin->debug.symbols)))
  31.235 +	{
  31.236 +		return SP_ERROR_FILE_FORMAT;
  31.237 +	}
  31.238 +
  31.239 +	if (m_pPlugin->num_publics > 0)
  31.240 +	{
  31.241 +		m_PubFuncs = new CFunction *[m_pPlugin->num_publics];
  31.242 +		memset(m_PubFuncs, 0, sizeof(CFunction *) * m_pPlugin->num_publics);
  31.243 +		m_PubJitFuncs = new JitFunction *[m_pPlugin->num_publics];
  31.244 +		memset(m_PubJitFuncs, 0, sizeof(JitFunction *) * m_pPlugin->num_publics);
  31.245 +	}
  31.246 +
  31.247 +	m_pPlugin->profiler = g_engine2.GetProfiler();
  31.248 +	m_pCtx = new BaseContext(this);
  31.249 +	m_pCo = g_Jit.StartCompilation(this);
  31.250 +
  31.251 +	return SP_ERROR_NONE;
  31.252  }
  31.253  
  31.254  int BaseRuntime::FindNativeByName(const char *name, uint32_t *index)
  31.255  {
  31.256  	int high;
  31.257  
  31.258 -	high = m_pPlugin->info.natives_num - 1;
  31.259 +	high = m_pPlugin->num_natives - 1;
  31.260  
  31.261 -	for (uint32_t i=0; i<m_pPlugin->info.natives_num; i++)
  31.262 +	for (uint32_t i=0; i<m_pPlugin->num_natives; i++)
  31.263  	{
  31.264  		if (strcmp(m_pPlugin->natives[i].name, name) == 0)
  31.265  		{
  31.266 @@ -80,7 +245,7 @@
  31.267  
  31.268  int BaseRuntime::GetNativeByIndex(uint32_t index, sp_native_t **native)
  31.269  {
  31.270 -	if (index >= m_pPlugin->info.natives_num)
  31.271 +	if (index >= m_pPlugin->num_natives)
  31.272  	{
  31.273  		return SP_ERROR_INDEX;
  31.274  	}
  31.275 @@ -96,7 +261,7 @@
  31.276  
  31.277  uint32_t BaseRuntime::GetNativesNum()
  31.278  {
  31.279 -	return m_pPlugin->info.natives_num;
  31.280 +	return m_pPlugin->num_natives;
  31.281  }
  31.282  
  31.283  int BaseRuntime::FindPublicByName(const char *name, uint32_t *index)
  31.284 @@ -104,7 +269,7 @@
  31.285  	int diff, high, low;
  31.286  	uint32_t mid;
  31.287  
  31.288 -	high = m_pPlugin->info.publics_num - 1;
  31.289 +	high = m_pPlugin->num_publics - 1;
  31.290  	low = 0;
  31.291  
  31.292  	while (low <= high)
  31.293 @@ -130,7 +295,7 @@
  31.294  
  31.295  int BaseRuntime::GetPublicByIndex(uint32_t index, sp_public_t **pblic)
  31.296  {
  31.297 -	if (index >= m_pPlugin->info.publics_num)
  31.298 +	if (index >= m_pPlugin->num_publics)
  31.299  	{
  31.300  		return SP_ERROR_INDEX;
  31.301  	}
  31.302 @@ -145,12 +310,12 @@
  31.303  
  31.304  uint32_t BaseRuntime::GetPublicsNum()
  31.305  {
  31.306 -	return m_pPlugin->info.publics_num;
  31.307 +	return m_pPlugin->num_publics;
  31.308  }
  31.309  
  31.310  int BaseRuntime::GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar)
  31.311  {
  31.312 -	if (index >= m_pPlugin->info.pubvars_num)
  31.313 +	if (index >= m_pPlugin->num_pubvars)
  31.314  	{
  31.315  		return SP_ERROR_INDEX;
  31.316  	}
  31.317 @@ -168,7 +333,7 @@
  31.318  	int diff, high, low;
  31.319  	uint32_t mid;
  31.320  
  31.321 -	high = m_pPlugin->info.pubvars_num - 1;
  31.322 +	high = m_pPlugin->num_pubvars - 1;
  31.323  	low = 0;
  31.324  
  31.325  	while (low <= high)
  31.326 @@ -182,9 +347,13 @@
  31.327  				*index = mid;
  31.328  			}
  31.329  			return SP_ERROR_NONE;
  31.330 -		} else if (diff < 0) {
  31.331 +		}
  31.332 +		else if (diff < 0)
  31.333 +		{
  31.334  			low = mid + 1;
  31.335 -		} else {
  31.336 +		}
  31.337 +		else
  31.338 +		{
  31.339  			high = mid - 1;
  31.340  		}
  31.341  	}
  31.342 @@ -194,12 +363,12 @@
  31.343  
  31.344  int BaseRuntime::GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr)
  31.345  {
  31.346 -	if (index >= m_pPlugin->info.pubvars_num)
  31.347 +	if (index >= m_pPlugin->num_pubvars)
  31.348  	{
  31.349  		return SP_ERROR_INDEX;
  31.350  	}
  31.351  
  31.352 -	*local_addr = m_pPlugin->info.pubvars[index].address;
  31.353 +	*local_addr = (uint8_t *)m_pPlugin->pubvars[index].offs - m_pPlugin->memory;
  31.354  	*phys_addr = m_pPlugin->pubvars[index].offs;
  31.355  
  31.356  	return SP_ERROR_NONE;
  31.357 @@ -207,7 +376,7 @@
  31.358  
  31.359  uint32_t BaseRuntime::GetPubVarsNum()
  31.360  {
  31.361 -	return m_pPlugin->info.pubvars_num;
  31.362 +	return m_pPlugin->num_pubvars;
  31.363  }
  31.364  
  31.365  IPluginContext *BaseRuntime::GetDefaultContext()
  31.366 @@ -217,35 +386,9 @@
  31.367  
  31.368  IPluginDebugInfo *BaseRuntime::GetDebugInfo()
  31.369  {
  31.370 -	if (!IsDebugging())
  31.371 -	{
  31.372 -		return NULL;
  31.373 -	}
  31.374 -
  31.375  	return &m_Debug;
  31.376  }
  31.377  
  31.378 -void BaseRuntime::RefreshFunctionCache()
  31.379 -{
  31.380 -	if (m_PubFuncs != NULL)
  31.381 -	{
  31.382 -		sp_public_t *pub;
  31.383 -		for (uint32_t i = 0; i < m_pPlugin->info.publics_num; i++)
  31.384 -		{
  31.385 -			if (m_PubFuncs[i] == NULL)
  31.386 -			{
  31.387 -				continue;
  31.388 -			}
  31.389 -			if (GetPublicByIndex(i, &pub) != SP_ERROR_NONE)
  31.390 -			{
  31.391 -				continue;
  31.392 -			}
  31.393 -			m_PubFuncs[i]->Set(pub->code_offs, this, (i << 1) | 1, i);
  31.394 -		}
  31.395 -	}
  31.396 -
  31.397 -}
  31.398 -
  31.399  IPluginFunction *BaseRuntime::GetFunctionById(funcid_t func_id)
  31.400  {
  31.401  	CFunction *pFunc = NULL;
  31.402 @@ -253,26 +396,18 @@
  31.403  	if (func_id & 1)
  31.404  	{
  31.405  		func_id >>= 1;
  31.406 -		if (func_id >= m_pPlugin->info.publics_num)
  31.407 +		if (func_id >= m_pPlugin->num_publics)
  31.408  		{
  31.409  			return NULL;
  31.410  		}
  31.411  		pFunc = m_PubFuncs[func_id];
  31.412  		if (!pFunc)
  31.413  		{
  31.414 -			m_PubFuncs[func_id] = new CFunction(m_pPlugin->publics[func_id].code_offs, 
  31.415 -				this, 
  31.416 +			m_PubFuncs[func_id] = new CFunction(this, 
  31.417  				(func_id << 1) | 1,
  31.418  				func_id);
  31.419  			pFunc = m_PubFuncs[func_id];
  31.420  		}
  31.421 -		else if (pFunc->IsInvalidated())
  31.422 -		{
  31.423 -			pFunc->Set(m_pPlugin->publics[func_id].code_offs, 
  31.424 -				this,
  31.425 -				(func_id << 1) | 1,
  31.426 -				func_id);
  31.427 -		}
  31.428  	}
  31.429  
  31.430  	return pFunc;
  31.431 @@ -294,30 +429,17 @@
  31.432  		GetPublicByIndex(index, &pub);
  31.433  		if (pub)
  31.434  		{
  31.435 -			m_PubFuncs[index] = new CFunction(pub->code_offs, this, (index << 1) | 1, index);
  31.436 +			m_PubFuncs[index] = new CFunction(this, (index << 1) | 1, index);
  31.437  		}
  31.438  		pFunc = m_PubFuncs[index];
  31.439  	}
  31.440 -	else if (pFunc->IsInvalidated())
  31.441 -	{
  31.442 -		sp_public_t *pub = NULL;
  31.443 -		GetPublicByIndex(index, &pub);
  31.444 -		if (pub)
  31.445 -		{
  31.446 -			pFunc->Set(pub->code_offs, this, (index << 1) | 1, index);
  31.447 -		}
  31.448 -		else
  31.449 -		{
  31.450 -			pFunc = NULL;
  31.451 -		}
  31.452 -	}
  31.453  
  31.454  	return pFunc;
  31.455  }
  31.456  
  31.457  bool BaseRuntime::IsDebugging()
  31.458  {
  31.459 -	return ((m_pPlugin->run_flags & SPFLAG_PLUGIN_DEBUG) == SPFLAG_PLUGIN_DEBUG);
  31.460 +	return true;
  31.461  }
  31.462  
  31.463  void BaseRuntime::SetPauseState(bool paused)
  31.464 @@ -345,8 +467,6 @@
  31.465  	mem += sizeof(sp_plugin_t);
  31.466  	mem += sizeof(BaseContext);
  31.467  	mem += m_pPlugin->base_size;
  31.468 -	mem += m_pPlugin->jit_codesize;
  31.469 -	mem += m_pPlugin->jit_memsize;
  31.470  
  31.471  	return mem;
  31.472  }
  31.473 @@ -356,3 +476,49 @@
  31.474  	return m_pCtx;
  31.475  }
  31.476  
  31.477 +int BaseRuntime::ApplyCompilationOptions(ICompilation *co)
  31.478 +{
  31.479 +	if (co == NULL)
  31.480 +	{
  31.481 +		return SP_ERROR_NONE;
  31.482 +	}
  31.483 +
  31.484 +	m_pCo = g_Jit.ApplyOptions(m_pCo, co);
  31.485 +
  31.486 +	return SP_ERROR_NONE;
  31.487 +}
  31.488 +
  31.489 +JitFunction *BaseRuntime::GetJittedFunction(uint32_t idx)
  31.490 +{
  31.491 +	assert(idx <= m_NumFuncs);
  31.492 +
  31.493 +	if (idx == 0 || idx > m_NumFuncs)
  31.494 +	{
  31.495 +		return NULL;
  31.496 +	}
  31.497 +
  31.498 +	return m_FuncCache[idx - 1];
  31.499 +}
  31.500 +
  31.501 +uint32_t BaseRuntime::AddJittedFunction(JitFunction *fn)
  31.502 +{
  31.503 +	if (m_NumFuncs + 1 > m_MaxFuncs)
  31.504 +	{
  31.505 +		if (m_MaxFuncs == 0)
  31.506 +		{
  31.507 +			m_MaxFuncs = 8;
  31.508 +		}
  31.509 +		else
  31.510 +		{
  31.511 +			m_MaxFuncs *= 2;
  31.512 +		}
  31.513 +
  31.514 +		m_FuncCache = (JitFunction **)realloc(
  31.515 +			m_FuncCache,
  31.516 +			sizeof(JitFunction *) * m_MaxFuncs);
  31.517 +	}
  31.518 +
  31.519 +	m_FuncCache[m_NumFuncs++] = fn;
  31.520 +
  31.521 +	return m_NumFuncs;
  31.522 +}
    32.1 --- a/sourcepawn/jit/BaseRuntime.h	Sun Aug 10 05:39:25 2008 +0000
    32.2 +++ b/sourcepawn/jit/BaseRuntime.h	Fri Aug 15 05:22:26 2008 +0000
    32.3 @@ -6,6 +6,7 @@
    32.4  #include "sp_vm_function.h"
    32.5  
    32.6  class BaseContext;
    32.7 +class JitFunction;
    32.8  
    32.9  class DebugInfo : public IPluginDebugInfo
   32.10  {
   32.11 @@ -23,9 +24,10 @@
   32.12  class BaseRuntime : public SourcePawn::IPluginRuntime
   32.13  {
   32.14  public:
   32.15 -	BaseRuntime(sp_plugin_t *pl);
   32.16 +	BaseRuntime();
   32.17  	~BaseRuntime();
   32.18  public:
   32.19 +	virtual int CreateFromMemory(sp_file_hdr_t *hdr, uint8_t *base);
   32.20  	virtual bool IsDebugging();
   32.21  	virtual IPluginDebugInfo *GetDebugInfo();
   32.22  	virtual int FindNativeByName(const char *name, uint32_t *index);
   32.23 @@ -45,16 +47,23 @@
   32.24  	virtual void SetPauseState(bool paused);
   32.25  	virtual bool IsPaused();
   32.26  	virtual size_t GetMemUsage();
   32.27 +	JitFunction *GetJittedFunction(uint32_t idx);
   32.28 +	uint32_t AddJittedFunction(JitFunction *fn);
   32.29  public:
   32.30  	BaseContext *GetBaseContext();
   32.31  private:
   32.32 -	void ClearCompile();
   32.33 -	void RefreshFunctionCache();
   32.34 +	sp_plugin_t m_plugin;
   32.35 +	unsigned int m_NumFuncs;
   32.36 +	unsigned int m_MaxFuncs;
   32.37 +	JitFunction **m_FuncCache;
   32.38  public:
   32.39  	DebugInfo m_Debug;
   32.40  	sp_plugin_t *m_pPlugin;
   32.41  	BaseContext *m_pCtx;
   32.42  	CFunction **m_PubFuncs;
   32.43 +	JitFunction **m_PubJitFuncs;
   32.44 +	ICompilation *m_pCo;
   32.45 +	unsigned int m_CompSerial;
   32.46  };
   32.47  
   32.48  #endif //_INCLUDE_SOURCEPAWN_JIT_RUNTIME_H_
    33.1 --- a/sourcepawn/jit/Makefile	Sun Aug 10 05:39:25 2008 +0000
    33.2 +++ b/sourcepawn/jit/Makefile	Fri Aug 15 05:22:26 2008 +0000
    33.3 @@ -1,98 +1,110 @@
    33.4 -# (C)2004-2008 SourceMod Development Team
    33.5 -# Makefile written by David "BAILOPAN" Anderson
    33.6 -
    33.7 -SMSDK = ../..
    33.8 -SOURCEHOOK = ../../../sourcemm-1.6/sourcehook
    33.9 -
   33.10 -#####################################
   33.11 -### EDIT BELOW FOR OTHER PROJECTS ###
   33.12 -#####################################
   33.13 -
   33.14 -PROJECT = sourcepawn.jit.x86
   33.15 -
   33.16 -OBJECTS = dll_exports.cpp 	\
   33.17 -	x86/jit_x86.cpp 	\
   33.18 -	x86/opcode_helpers.cpp	\
   33.19 -	sp_vm_basecontext.cpp	\
   33.20 -	sp_vm_engine.cpp	\
   33.21 -	sp_vm_function.cpp	\
   33.22 -	engine2.cpp		\
   33.23 -	BaseRuntime.cpp		\
   33.24 -	zlib/adler32.c		\
   33.25 -	zlib/compress.c		\
   33.26 -	zlib/crc32.c		\
   33.27 -	zlib/deflate.c		\
   33.28 -	zlib/gzio.c		\
   33.29 -	zlib/infback.c		\
   33.30 -	zlib/inffast.c		\
   33.31 -	zlib/inflate.c		\
   33.32 -	zlib/inftrees.c		\
   33.33 -	zlib/trees.c		\
   33.34 -	zlib/uncompr.c		\
   33.35 -	zlib/zutil.c
   33.36 -
   33.37 -##############################################
   33.38 -### CONFIGURE ANY OTHER FLAGS/OPTIONS HERE ###
   33.39 -##############################################
   33.40 -
   33.41 -C_OPT_FLAGS = -DNDEBUG -O3 -funroll-loops -pipe -fno-strict-aliasing
   33.42 -C_DEBUG_FLAGS = -D_DEBUG -DDEBUG -g -ggdb3
   33.43 -C_GCC4_FLAGS = -fvisibility=hidden
   33.44 -CPP_GCC4_FLAGS = -fvisibility-inlines-hidden
   33.45 -CPP = gcc-4.1
   33.46 -
   33.47 -LINK = -static-libgcc
   33.48 -
   33.49 -INCLUDE = -I. -I.. -I$(SMSDK)/public -I$(SMSDK)/public/jit -I$(SMSDK)/public/jit/x86 \
   33.50 -	-I$(SMSDK)/public/sourcepawn -I$(SOURCEHOOK)
   33.51 -
   33.52 -CFLAGS += -D_LINUX -Dstricmp=strcasecmp -D_stricmp=strcasecmp -D_strnicmp=strncasecmp -Dstrnicmp=strncasecmp \
   33.53 -	-D_snprintf=snprintf -D_vsnprintf=vsnprintf -D_alloca=alloca -Dstrcmpi=strcasecmp -Wall -DHAVE_STDINT_H \
   33.54 -	-m32
   33.55 -CPPFLAGS += -Wno-non-virtual-dtor -fno-exceptions -fno-rtti
   33.56 -
   33.57 -################################################
   33.58 -### DO NOT EDIT BELOW HERE FOR MOST PROJECTS ###
   33.59 -################################################
   33.60 -
   33.61 -ifeq "$(DEBUG)" "true"
   33.62 -	BIN_DIR = Debug
   33.63 -	CFLAGS += $(C_DEBUG_FLAGS)
   33.64 -else
   33.65 -	BIN_DIR = Release
   33.66 -	CFLAGS += $(C_OPT_FLAGS)
   33.67 -endif
   33.68 -
   33.69 -GCC_VERSION := $(shell $(CPP) -dumpversion >&1 | cut -b1)
   33.70 -ifeq "$(GCC_VERSION)" "4"
   33.71 -	CFLAGS += $(C_GCC4_FLAGS)
   33.72 -	CPPFLAGS += $(CPP_GCC4_FLAGS)
   33.73 -endif
   33.74 -
   33.75 -BINARY = $(PROJECT).so
   33.76 -
   33.77 -OBJ_LINUX := $(OBJECTS:%.cpp=$(BIN_DIR)/%.o)
   33.78 -OBJ_LINUX := $(OBJ_LINUX:%.c=$(BIN_DIR)/%.o)
   33.79 -
   33.80 -$(BIN_DIR)/%.o: %.c
   33.81 -	$(CPP) $(INCLUDE) $(CFLAGS) -o $@ -c $<
   33.82 -
   33.83 -$(BIN_DIR)/%.o: %.cpp
   33.84 -	$(CPP) $(INCLUDE) $(CFLAGS) $(CPPFLAGS) -o $@ -c $<
   33.85 -
   33.86 -all:
   33.87 -	mkdir -p $(BIN_DIR)/x86
   33.88 -	mkdir -p $(BIN_DIR)/zlib
   33.89 -	$(MAKE) -f Makefile jit
   33.90 -
   33.91 -jit: $(OBJ_LINUX)
   33.92 -	$(CPP) $(INCLUDE) $(OBJ_LINUX) $(LINK) -m32 -shared -ldl -lm -o$(BIN_DIR)/$(BINARY)
   33.93 -
   33.94 -debug:
   33.95 -	$(MAKE) -f Makefile all DEBUG=true
   33.96 -
   33.97 -default: all
   33.98 -
   33.99 -clean:
  33.100 -	rm -rf $(BIN_DIR)/*.o
  33.101 -	rm -rf $(BIN_DIR)/$(BINARY)
  33.102 +# (C)2004-2008 SourceMod Development Team
  33.103 +# Makefile written by David "BAILOPAN" Anderson
  33.104 +
  33.105 +SMSDK = ../..
  33.106 +SOURCEHOOK = ../../../sourcemm-1.6/sourcehook
  33.107 +
  33.108 +#####################################
  33.109 +### EDIT BELOW FOR OTHER PROJECTS ###
  33.110 +#####################################
  33.111 +
  33.112 +PROJECT = sourcepawn.jit.x86
  33.113 +
  33.114 +OBJECTS = dll_exports.cpp 	\
  33.115 +	x86/jit_x86.cpp			\
  33.116 +	x86/opcode_helpers.cpp	\
  33.117 +	sp_vm_basecontext.cpp	\
  33.118 +	sp_vm_engine.cpp	\
  33.119 +	sp_vm_function.cpp	\
  33.120 +	engine2.cpp			\
  33.121 +	BaseRuntime.cpp		\
  33.122 +	jit_function.cpp	\
  33.123 +	zlib/adler32.c		\
  33.124 +	zlib/compress.c		\
  33.125 +	zlib/crc32.c		\
  33.126 +	zlib/deflate.c		\
  33.127 +	zlib/gzio.c			\
  33.128 +	zlib/infback.c		\
  33.129 +	zlib/inffast.c		\
  33.130 +	zlib/inflate.c		\
  33.131 +	zlib/inftrees.c		\
  33.132 +	zlib/trees.c		\
  33.133 +	zlib/uncompr.c		\
  33.134 +	zlib/zutil.c		\
  33.135 +
  33.136 +OBJECTS += ../../knight/shared/KeCodeAllocator.cpp
  33.137 +
  33.138 +##############################################
  33.139 +### CONFIGURE ANY OTHER FLAGS/OPTIONS HERE ###
  33.140 +##############################################
  33.141 +
  33.142 +C_OPT_FLAGS = -DNDEBUG -O3 -funroll-loops -pipe -fno-strict-aliasing
  33.143 +C_DEBUG_FLAGS = -D_DEBUG -DDEBUG -g -ggdb3
  33.144 +C_GCC4_FLAGS = -fvisibility=hidden
  33.145 +CPP_GCC4_FLAGS = -fvisibility-inlines-hidden
  33.146 +CPP = gcc-4.1
  33.147 +
  33.148 +LINK = -static-libgcc
  33.149 +
  33.150 +INCLUDE = -I. -I.. -I$(SMSDK)/public -I$(SMSDK)/public/jit -I$(SMSDK)/public/jit/x86 \
  33.151 +	-I$(SMSDK)/public/sourcepawn -I$(SOURCEHOOK) -I$(SMSDK)/knight/shared -Ix86
  33.152 +
  33.153 +CFLAGS += -D_LINUX -Dstricmp=strcasecmp -D_stricmp=strcasecmp -D_strnicmp=strncasecmp -Dstrnicmp=strncasecmp \
  33.154 +	-D_snprintf=snprintf -D_vsnprintf=vsnprintf -D_alloca=alloca -Dstrcmpi=strcasecmp -Wall -DHAVE_STDINT_H \
  33.155 +	-m32 -Wno-uninitialized -Werror
  33.156 +CPPFLAGS += -Wno-non-virtual-dtor -fno-exceptions -fno-rtti
  33.157 +
  33.158 +################################################
  33.159 +### DO NOT EDIT BELOW HERE FOR MOST PROJECTS ###
  33.160 +################################################
  33.161 +
  33.162 +ifeq "$(DEBUG)" "true"
  33.163 +	BIN_DIR = Debug
  33.164 +	CFLAGS += $(C_DEBUG_FLAGS)
  33.165 +else
  33.166 +	BIN_DIR = Release
  33.167 +	CFLAGS += $(C_OPT_FLAGS)
  33.168 +endif
  33.169 +
  33.170 +GCC_VERSION := $(shell $(CPP) -dumpversion >&1 | cut -b1)
  33.171 +ifeq "$(GCC_VERSION)" "4"
  33.172 +	CFLAGS += $(C_GCC4_FLAGS)
  33.173 +	CPPFLAGS += $(CPP_GCC4_FLAGS)
  33.174 +endif
  33.175 +
  33.176 +BINARY = $(PROJECT).so
  33.177 +
  33.178 +OBJ_LINUX := $(OBJECTS:../../knight/shared/%.cpp=$(BIN_DIR)/knight/%.o)
  33.179 +OBJ_LINUX := $(OBJ_LINUX:%.cpp=$(BIN_DIR)/%.o)
  33.180 +OBJ_LINUX := $(OBJ_LINUX:%.c=$(BIN_DIR)/%.o)
  33.181 +
  33.182 +default: all
  33.183 +
  33.184 +$(BIN_DIR)/%.o: %.c
  33.185 +	$(CPP) $(INCLUDE) $(CFLAGS) -o $@ -c $<
  33.186 +
  33.187 +$(BIN_DIR)/%.o: %.cpp
  33.188 +	$(CPP) $(INCLUDE) $(CFLAGS) $(CPPFLAGS) -o $@ -c $<
  33.189 +
  33.190 +$(BIN_DIR)/knight/%.o: ../../knight/shared/%.cpp
  33.191 +	$(CPP) $(INCLUDE) $(CFLAGS) $(CPPFLAGS) -o $@ -c $<
  33.192 +
  33.193 +all:
  33.194 +	mkdir -p $(BIN_DIR)/x86
  33.195 +	mkdir -p $(BIN_DIR)/zlib
  33.196 +	mkdir -p $(BIN_DIR)/knight
  33.197 +	$(MAKE) -f Makefile jit
  33.198 +
  33.199 +jit: $(OBJ_LINUX)
  33.200 +	$(CPP) $(INCLUDE) $(OBJ_LINUX) $(LINK) -m32 -shared -ldl -lm -o$(BIN_DIR)/$(BINARY)
  33.201 +
  33.202 +debug:
  33.203 +	$(MAKE) -f Makefile all DEBUG=true
  33.204 +
  33.205 +clean:
  33.206 +	rm -rf $(BIN_DIR)/x86/*.o
  33.207 +	rm -rf $(BIN_DIR)/zlib/*.o
  33.208 +	rm -rf $(BIN_DIR)/knight/*.o
  33.209 +	rm -rf $(BIN_DIR)/*.o
  33.210 +	rm -rf $(BIN_DIR)/$(BINARY)
  33.211 +
    34.1 --- a/sourcepawn/jit/engine2.cpp	Sun Aug 10 05:39:25 2008 +0000
    34.2 +++ b/sourcepawn/jit/engine2.cpp	Fri Aug 15 05:22:26 2008 +0000
    34.3 @@ -15,113 +15,9 @@
    34.4  	m_Profiler = NULL;
    34.5  }
    34.6  
    34.7 -sp_plugin_t *_ReadPlugin(sp_file_hdr_t *hdr, uint8_t *base, sp_plugin_t *plugin, int *err)
    34.8 -{
    34.9 -	char *nameptr;
   34.10 -	uint8_t sectnum = 0;
   34.11 -	sp_file_section_t *secptr = (sp_file_section_t *)(base + sizeof(sp_file_hdr_t));
   34.12 -
   34.13 -	memset(plugin, 0, sizeof(sp_plugin_t));
   34.14 -
   34.15 -	plugin->base = base;
   34.16 -
   34.17 -	while (sectnum < hdr->sections)
   34.18 -	{
   34.19 -		nameptr = (char *)(base + hdr->stringtab + secptr->nameoffs);
   34.20 -
   34.21 -		if (!(plugin->pcode) && !strcmp(nameptr, ".code"))
   34.22 -		{
   34.23 -			sp_file_code_t *cod = (sp_file_code_t *)(base + secptr->dataoffs);
   34.24 -			plugin->pcode = base + secptr->dataoffs + cod->code;
   34.25 -			plugin->pcode_size = cod->codesize;
   34.26 -			plugin->flags = cod->flags;
   34.27 -		}
   34.28 -		else if (!(plugin->data) && !strcmp(nameptr, ".data"))
   34.29 -		{
   34.30 -			sp_file_data_t *dat = (sp_file_data_t *)(base + secptr->dataoffs);
   34.31 -			plugin->data = base + secptr->dataoffs + dat->data;
   34.32 -			plugin->data_size = dat->datasize;
   34.33 -			plugin->mem_size = dat->memsize;
   34.34 -			plugin->memory = new uint8_t[plugin->mem_size];
   34.35 -			memcpy(plugin->memory, plugin->data, plugin->data_size);
   34.36 -		}
   34.37 -		else if (!(plugin->info.publics) && !strcmp(nameptr, ".publics"))
   34.38 -		{
   34.39 -			plugin->info.publics_num = secptr->size / sizeof(sp_file_publics_t);
   34.40 -			plugin->info.publics = (sp_file_publics_t *)(base + secptr->dataoffs);
   34.41 -		}
   34.42 -		else if (!(plugin->info.pubvars) && !strcmp(nameptr, ".pubvars"))
   34.43 -		{
   34.44 -			plugin->info.pubvars_num = secptr->size / sizeof(sp_file_pubvars_t);
   34.45 -			plugin->info.pubvars = (sp_file_pubvars_t *)(base + secptr->dataoffs);
   34.46 -		}
   34.47 -		else if (!(plugin->info.natives) && !strcmp(nameptr, ".natives"))
   34.48 -		{
   34.49 -			plugin->info.natives_num = secptr->size / sizeof(sp_file_natives_t);
   34.50 -			plugin->info.natives = (sp_file_natives_t *)(base + secptr->dataoffs);
   34.51 -		}
   34.52 -		else if (!(plugin->info.stringbase) && !strcmp(nameptr, ".names"))
   34.53 -		{
   34.54 -			plugin->info.stringbase = (const char *)(base + secptr->dataoffs);
   34.55 -		}
   34.56 -		else if (!(plugin->debug.files) && !strcmp(nameptr, ".dbg.files"))
   34.57 -		{
   34.58 -			plugin->debug.files = (sp_fdbg_file_t *)(base + secptr->dataoffs);
   34.59 -		}
   34.60 -		else if (!(plugin->debug.lines) && !strcmp(nameptr, ".dbg.lines"))
   34.61 -		{
   34.62 -			plugin->debug.lines = (sp_fdbg_line_t *)(base + secptr->dataoffs);
   34.63 -		}
   34.64 -		else if (!(plugin->debug.symbols) && !strcmp(nameptr, ".dbg.symbols"))
   34.65 -		{
   34.66 -			plugin->debug.symbols = (sp_fdbg_symbol_t *)(base + secptr->dataoffs);
   34.67 -		}
   34.68 -		else if (!(plugin->debug.lines_num) && !strcmp(nameptr, ".dbg.info"))
   34.69 -		{
   34.70 -			sp_fdbg_info_t *inf = (sp_fdbg_info_t *)(base + secptr->dataoffs);
   34.71 -			plugin->debug.files_num = inf->num_files;
   34.72 -			plugin->debug.lines_num = inf->num_lines;
   34.73 -			plugin->debug.syms_num = inf->num_syms;
   34.74 -		}
   34.75 -		else if (!(plugin->debug.stringbase) && !strcmp(nameptr, ".dbg.strings"))
   34.76 -		{
   34.77 -			plugin->debug.stringbase = (const char *)(base + secptr->dataoffs);
   34.78 -		}
   34.79 -
   34.80 -		secptr++;
   34.81 -		sectnum++;
   34.82 -	}
   34.83 -
   34.84 -	if (!(plugin->pcode) || !(plugin->data) || !(plugin->info.stringbase))
   34.85 -	{
   34.86 -		goto return_error;
   34.87 -	}
   34.88 -
   34.89 -	if ((plugin->flags & SP_FLAG_DEBUG) && (!(plugin->debug.files) || !(plugin->debug.lines) || !(plugin->debug.symbols)))
   34.90 -	{
   34.91 -		goto return_error;
   34.92 -	}
   34.93 -
   34.94 -	if (err)
   34.95 -	{
   34.96 -		*err = SP_ERROR_NONE;
   34.97 -	}
   34.98 -
   34.99 -	return plugin;
  34.100 -
  34.101 -return_error:
  34.102 -	if (err)
  34.103 -	{
  34.104 -		*err = SP_ERROR_FILE_FORMAT;
  34.105 -	}
  34.106 -
  34.107 -	return NULL;
  34.108 -}
  34.109 -
  34.110  IPluginRuntime *SourcePawnEngine2::LoadPlugin(ICompilation *co, const char *file, int *err)
  34.111  {
  34.112  	sp_file_hdr_t hdr;
  34.113 -	sp_plugin_t *plugin;
  34.114  	uint8_t *base;
  34.115  	int z_result;
  34.116  	int error;
  34.117 @@ -141,7 +37,6 @@
  34.118  	if (hdr.magic != SPFILE_MAGIC)
  34.119  	{
  34.120  		error = SP_ERROR_FILE_FORMAT;
  34.121 -		fclose(fp);
  34.122  		goto return_error;
  34.123  	}
  34.124  
  34.125 @@ -168,7 +63,6 @@
  34.126  				free(sectheader);
  34.127  				free(uncompdata);
  34.128  				error = SP_ERROR_DECOMPRESSOR;
  34.129 -				fclose(fp);
  34.130  				goto return_error;
  34.131  			}
  34.132  
  34.133 @@ -190,40 +84,41 @@
  34.134  	default:
  34.135  		{
  34.136  			error = SP_ERROR_DECOMPRESSOR;
  34.137 -			fclose(fp);
  34.138  			goto return_error;
  34.139  		}
  34.140  	}
  34.141  
  34.142 -	fclose(fp);
  34.143  
  34.144 -	plugin = new sp_plugin_t;
  34.145 -
  34.146 -	memset(plugin, 0, sizeof(sp_plugin_t));
  34.147 -
  34.148 -	plugin->base_size = hdr.imagesize;
  34.149 -	if (!_ReadPlugin(&hdr, base, plugin, err))
  34.150 +	pRuntime = new BaseRuntime();
  34.151 +	if ((error = pRuntime->CreateFromMemory(&hdr, base)) != SP_ERROR_NONE)
  34.152  	{
  34.153 -		delete plugin;
  34.154 -		free(base);
  34.155 -		return NULL;
  34.156 +		delete pRuntime;
  34.157 +		goto return_error;
  34.158  	}
  34.159  
  34.160 -	pRuntime = new BaseRuntime(plugin);
  34.161 -
  34.162 -	if (co == NULL)
  34.163 +	size_t len;
  34.164 +	
  34.165 +	len = strlen(file);
  34.166 +	for (size_t i = len - 1; i >= 0 && i < len; i--)
  34.167  	{
  34.168 -		co = g_Jit1.StartCompilation(pRuntime);
  34.169 +		if (file[i] == '/' 
  34.170 +		#if defined WIN32
  34.171 +			|| file[i] == '\\'
  34.172 +		#endif
  34.173 +		)
  34.174 +		{
  34.175 +			pRuntime->m_pPlugin->name = strdup(&file[i+1]);
  34.176 +			break;
  34.177 +		}
  34.178  	}
  34.179  
  34.180 -
  34.181 -	*err = pRuntime->ApplyCompilationOptions(co);
  34.182 -	if (*err != SP_ERROR_NONE)
  34.183 +	if (pRuntime->m_pPlugin->name == NULL)
  34.184  	{
  34.185 -		delete pRuntime;
  34.186 -		return NULL;
  34.187 +		pRuntime->m_pPlugin->name = strdup(file);
  34.188  	}
  34.189  
  34.190 +	pRuntime->ApplyCompilationOptions(co);
  34.191 +
  34.192  	return pRuntime;
  34.193  
  34.194  return_error:
  34.195 @@ -234,12 +129,12 @@
  34.196  
  34.197  SPVM_NATIVE_FUNC SourcePawnEngine2::CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData)
  34.198  {
  34.199 -	return g_Jit1.CreateFakeNative(callback, pData);
  34.200 +	return g_Jit.CreateFakeNative(callback, pData);
  34.201  }
  34.202  
  34.203  void SourcePawnEngine2::DestroyFakeNative(SPVM_NATIVE_FUNC func)
  34.204  {
  34.205 -	g_Jit1.DestroyFakeNative(func);
  34.206 +	g_Jit.DestroyFakeNative(func);
  34.207  }
  34.208  
  34.209  const char *SourcePawnEngine2::GetEngineName()
  34.210 @@ -274,10 +169,20 @@
  34.211  
  34.212  ICompilation *SourcePawnEngine2::StartCompilation()
  34.213  {
  34.214 -	return g_Jit1.StartCompilation();
  34.215 +	return g_Jit.StartCompilation();
  34.216  }
  34.217  
  34.218  const char *SourcePawnEngine2::GetErrorString(int err)
  34.219  {
  34.220  	return g_engine1.GetErrorString(err);
  34.221  }
  34.222 +
  34.223 +bool SourcePawnEngine2::Initialize()
  34.224 +{
  34.225 +	return g_Jit.InitializeJIT();
  34.226 +}
  34.227 +
  34.228 +void SourcePawnEngine2::Shutdown()
  34.229 +{
  34.230 +	g_Jit.ShutdownJIT();
  34.231 +}
    35.1 --- a/sourcepawn/jit/engine2.h	Sun Aug 10 05:39:25 2008 +0000
    35.2 +++ b/sourcepawn/jit/engine2.h	Fri Aug 15 05:22:26 2008 +0000
    35.3 @@ -23,6 +23,8 @@
    35.4  		void SetProfiler(IProfiler *profiler);
    35.5  		ICompilation *StartCompilation();
    35.6  		const char *GetErrorString(int err);
    35.7 +		bool Initialize();
    35.8 +		void Shutdown();
    35.9  	public:
   35.10  		IProfiler *GetProfiler();
   35.11  	private:
    36.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    36.2 +++ b/sourcepawn/jit/jit_function.cpp	Fri Aug 15 05:22:26 2008 +0000
    36.3 @@ -0,0 +1,23 @@
    36.4 +#include "jit_function.h"
    36.5 +#include "sp_vm_engine.h"
    36.6 +#include "jit_x86.h"
    36.7 +
    36.8 +JitFunction::JitFunction(void *entry_addr, cell_t pcode_offs)
    36.9 +: m_pEntryAddr(entry_addr), m_PcodeOffs(pcode_offs)
   36.10 +{
   36.11 +}
   36.12 +
   36.13 +JitFunction::~JitFunction()
   36.14 +{
   36.15 +	g_Jit.FreeCode(m_pEntryAddr);
   36.16 +}
   36.17 +
   36.18 +void *JitFunction::GetEntryAddress()
   36.19 +{
   36.20 +	return m_pEntryAddr;
   36.21 +}
   36.22 +
   36.23 +cell_t JitFunction::GetPCodeAddress()
   36.24 +{
   36.25 +	return m_PcodeOffs;
   36.26 +}
    37.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    37.2 +++ b/sourcepawn/jit/jit_function.h	Fri Aug 15 05:22:26 2008 +0000
    37.3 @@ -0,0 +1,19 @@
    37.4 +#ifndef _INCLUDE_SOURCEPAWN_JIT2_FUNCTION_H_
    37.5 +#define _INCLUDE_SOURCEPAWN_JIT2_FUNCTION_H_
    37.6 +
    37.7 +#include <sp_vm_types.h>
    37.8 +
    37.9 +class JitFunction
   37.10 +{
   37.11 +public:
   37.12 +	JitFunction(void *entry_addr, cell_t pcode_offs);
   37.13 +	~JitFunction();
   37.14 +public:
   37.15 +	void *GetEntryAddress();
   37.16 +	cell_t GetPCodeAddress();
   37.17 +private:
   37.18 +	void *m_pEntryAddr;
   37.19 +	cell_t m_PcodeOffs;
   37.20 +};
   37.21 +
   37.22 +#endif //_INCLUDE_SOURCEPAWN_JIT2_FUNCTION_H_
    38.1 --- a/sourcepawn/jit/jit_shared.h	Sun Aug 10 05:39:25 2008 +0000
    38.2 +++ b/sourcepawn/jit/jit_shared.h	Fri Aug 15 05:22:26 2008 +0000
    38.3 @@ -5,23 +5,11 @@
    38.4  
    38.5  using namespace SourcePawn;
    38.6  
    38.7 -/**
    38.8 -* @brief Information about the core plugin tables.  These may or may not be present!
    38.9 -*/
   38.10 -typedef struct sp_plugin_infotab_s
   38.11 -{
   38.12 -	const char *stringbase;		/**< base of string table */
   38.13 -	uint32_t	publics_num;	/**< number of publics */
   38.14 -	sp_file_publics_t *publics;	/**< public table */
   38.15 -	uint32_t	natives_num;	/**< number of natives */
   38.16 -	sp_file_natives_t *natives; /**< native table */
   38.17 -	uint32_t	pubvars_num;	/**< number of pubvars */
   38.18 -	sp_file_pubvars_t *pubvars;	/**< pubvars table */
   38.19 -} sp_plugin_infotab_t;
   38.20 +#define SP_MAX_RETURN_STACK		1024
   38.21  
   38.22  /**
   38.23 -* @brief Information about the plugin's debug tables.  These are all present if one is present.
   38.24 -*/
   38.25 + * @brief Information about the plugin's debug tables.  These are all present if one is present.
   38.26 + */
   38.27  typedef struct sp_plugin_debug_s
   38.28  {
   38.29  	const char *stringbase;		/**< base of string table */
   38.30 @@ -36,12 +24,12 @@
   38.31  class BaseContext;
   38.32  
   38.33  /**
   38.34 -* Breaks into a debugger
   38.35 -* Params:
   38.36 -*  [0] - plugin context
   38.37 -*  [1] - frm
   38.38 -*  [2] - cip
   38.39 -*/
   38.40 + * Breaks into a debugger
   38.41 + * Params:
   38.42 + *  [0] - plugin context
   38.43 + *  [1] - frm
   38.44 + *  [2] - cip
   38.45 + */
   38.46  typedef int (*SPVM_DEBUGBREAK)(BaseContext *, uint32_t, uint32_t);
   38.47  
   38.48  /**
   38.49 @@ -59,37 +47,40 @@
   38.50  		uint32_t	data_size;		/**< Size of data */
   38.51  		uint32_t	mem_size;		/**< Required memory space */
   38.52  		uint16_t	flags;			/**< Code flags */
   38.53 -		sp_plugin_infotab_t info;	/**< Base info table */
   38.54  		sp_plugin_debug_t   debug;	/**< Debug info table */
   38.55  		size_t		base_size;		/**< Size of the entire plugin base */
   38.56 -		void		*codebase;		/**< Base of generated code and memory */
   38.57 -		SPVM_DEBUGBREAK dbreak;		/**< Debug break function */
   38.58  		uint8_t		*memory;		/**< Data chunk */
   38.59 +		const char *stringbase;		/**< base of string table */
   38.60  		sp_public_t	*publics;		/**< Public functions table */
   38.61 +		uint32_t	num_publics;	/**< Number of publics. */
   38.62  		sp_pubvar_t	*pubvars;		/**< Public variables table */
   38.63 +		uint32_t	num_pubvars;	/**< Number of public variables */
   38.64  		sp_native_t	*natives;		/**< Natives table */
   38.65 -		sp_debug_file_t	*files;		/**< Files */
   38.66 -		sp_debug_line_t	*lines;		/**< Lines */
   38.67 -		sp_debug_symbol_t *symbols;	/**< Symbols */
   38.68 +		uint32_t	num_natives;	/**< Number of natives */
   38.69  		IProfiler *profiler;		/**< Pointer to IProfiler */
   38.70  		uint32_t	prof_flags;		/**< Profiling flags */
   38.71  		uint32_t	run_flags;		/**< Runtime flags */
   38.72 -		size_t		jit_codesize;	/**< JIT compiled codesize */
   38.73 -		size_t		jit_memsize;	/**< JIT additional memory */
   38.74 +		uint32_t	pcode_version;	/**< P-Code version number */
   38.75 +		char		*name;			/**< Plugin/script name */
   38.76  	} sp_plugin_t;
   38.77  }
   38.78  
   38.79  typedef struct sp_context_s
   38.80  {
   38.81 -	cell_t			hp;			/**< Heap pointer */
   38.82 -	cell_t			sp;			/**< Stack pointer */
   38.83 -	cell_t			frm;		/**< Frame pointer */
   38.84 -	int32_t			n_err;		/**< Error code set by a native */
   38.85 -	uint32_t		n_idx;		/**< Current native index being executed */
   38.86 -	void *			vm[8];		/**< VM-specific pointers */
   38.87 +	cell_t			hp;				/**< Heap pointer */
   38.88 +	cell_t			sp;				/**< Stack pointer */
   38.89 +	cell_t			frm;			/**< Frame pointer */
   38.90 +	int32_t			err_cip;		/**< Code pointer last error occurred in */
   38.91 +	int32_t			n_err;			/**< Error code set by a native */
   38.92 +	uint32_t		n_idx;			/**< Current native index being executed */
   38.93 +	void *			vm[8];			/**< VM-specific pointers */
   38.94 +	cell_t			rp;				/**< Return stack pointer */
   38.95 +	cell_t			rstk_cips[SP_MAX_RETURN_STACK];
   38.96  } sp_context_t;
   38.97  
   38.98 -#define SPFLAG_PLUGIN_DEBUG			(1<<0)
   38.99 +//#define SPFLAG_PLUGIN_DEBUG			(1<<0)
  38.100  #define SPFLAG_PLUGIN_PAUSED		(1<<1)
  38.101  
  38.102 +#define INVALID_CIP			0xFFFFFFFF
  38.103 +
  38.104  #endif //_INCLUDE_SOURCEPAWN_JIT_SHARED_H_
    39.1 --- a/sourcepawn/jit/jit_version.h	Sun Aug 10 05:39:25 2008 +0000
    39.2 +++ b/sourcepawn/jit/jit_version.h	Fri Aug 15 05:22:26 2008 +0000
    39.3 @@ -32,7 +32,7 @@
    39.4  #ifndef _INCLUDE_JIT_VERSION_H_
    39.5  #define _INCLUDE_JIT_VERSION_H_
    39.6  
    39.7 -#define SVN_FULL_VERSION	"1.1.0-svn"
    39.8 -#define SVN_FILE_VERSION	1,1,0,2218
    39.9 +#define SVN_FULL_VERSION	"1.2.0-svn"
   39.10 +#define SVN_FILE_VERSION	1,2,0,2218
   39.11  
   39.12  #endif //_INCLUDE_JIT_VERSION_H_
    40.1 --- a/sourcepawn/jit/sp_vm_basecontext.cpp	Sun Aug 10 05:39:25 2008 +0000
    40.2 +++ b/sourcepawn/jit/sp_vm_basecontext.cpp	Fri Aug 15 05:22:26 2008 +0000
    40.3 @@ -51,12 +51,43 @@
    40.4  	m_InExec = false;
    40.5  	m_CustomMsg = false;
    40.6  
    40.7 -	m_pNullVec = NULL;
    40.8 -	m_pNullString = NULL;
    40.9 +	/* Initialize the null references */
   40.10 +	uint32_t index;
   40.11 +	if (FindPubvarByName("NULL_VECTOR", &index) == SP_ERROR_NONE)
   40.12 +	{
   40.13 +		sp_pubvar_t *pubvar;
   40.14 +		GetPubvarByIndex(index, &pubvar);
   40.15 +		m_pNullVec = pubvar->offs;
   40.16 +	}
   40.17 +	else
   40.18 +	{
   40.19 +		m_pNullVec = NULL;
   40.20 +	}
   40.21 +
   40.22 +	if (FindPubvarByName("NULL_STRING", &index) == SP_ERROR_NONE)
   40.23 +	{
   40.24 +		sp_pubvar_t *pubvar;
   40.25 +		GetPubvarByIndex(index, &pubvar);
   40.26 +		m_pNullString = pubvar->offs;
   40.27 +	}
   40.28 +	else
   40.29 +	{
   40.30 +		m_pNullString = NULL;
   40.31 +	}
   40.32 +
   40.33 +	m_ctx.hp = m_pPlugin->data_size;
   40.34 +	m_ctx.sp = m_pPlugin->mem_size - sizeof(cell_t);
   40.35 +	m_ctx.frm = m_ctx.sp;
   40.36 +	m_ctx.n_err = SP_ERROR_NONE;
   40.37 +	m_ctx.n_idx = SP_ERROR_NONE;
   40.38 +	m_ctx.rp = 0;
   40.39 +
   40.40 +	g_Jit.SetupContextVars(m_pRuntime, this, &m_ctx);
   40.41  }
   40.42  
   40.43  BaseContext::~BaseContext()
   40.44  {
   40.45 +	g_Jit.FreeContextVars(&m_ctx);
   40.46  }
   40.47  
   40.48  IVirtualMachine *BaseContext::GetVirtualMachine()
   40.49 @@ -76,7 +107,7 @@
   40.50  
   40.51  bool BaseContext::IsDebugging()
   40.52  {
   40.53 -	return m_pRuntime->IsDebugging();
   40.54 +	return true;
   40.55  }
   40.56  
   40.57  int BaseContext::SetDebugBreak(void *newpfn, void *oldpfn)
   40.58 @@ -517,15 +548,15 @@
   40.59  	int serial;
   40.60  	cell_t *sp;
   40.61  	funcid_t fnid;
   40.62 +	JitFunction *fn;
   40.63  	sp_public_t *pubfunc;
   40.64  	cell_t _ignore_result;
   40.65 +	unsigned int public_id;
   40.66  
   40.67  	fnid = function->GetFunctionID();
   40.68  
   40.69  	if (fnid & 1)
   40.70 -	{
   40.71 -		unsigned int public_id;
   40.72 -		
   40.73 +	{	
   40.74  		public_id = fnid >> 1;
   40.75  
   40.76  		if (m_pRuntime->GetPublicByIndex(public_id, &pubfunc) != SP_ERROR_NONE)
   40.77 @@ -560,16 +591,40 @@
   40.78  		serial = m_pPlugin->profiler->OnCallbackBegin(this, pubfunc);
   40.79  	}
   40.80  
   40.81 +	/* See if we have to compile the callee. */
   40.82 +	if ((fn = m_pRuntime->m_PubJitFuncs[public_id]) == NULL)
   40.83 +	{
   40.84 +		uint32_t func_idx;
   40.85 +
   40.86 +		/* We might not have to - check pcode offset. */
   40.87 +		if ((func_idx = FuncLookup((CompData *)m_pRuntime->m_pCo, pubfunc->code_offs)) != 0)
   40.88 +		{
   40.89 +			fn = m_pRuntime->GetJittedFunction(func_idx);
   40.90 +			assert(fn != NULL);
   40.91 +			m_pRuntime->m_PubJitFuncs[public_id] = fn;
   40.92 +		}
   40.93 +		else
   40.94 +		{
   40.95 +			if ((fn = g_Jit.CompileFunction(m_pRuntime, pubfunc->code_offs, &ir)) == NULL)
   40.96 +			{
   40.97 +				return ir;
   40.98 +			}
   40.99 +			m_pRuntime->m_PubJitFuncs[public_id] = fn;
  40.100 +		}
  40.101 +	}
  40.102 +
  40.103  	/* Save our previous state. */
  40.104  
  40.105  	bool save_exec;
  40.106  	uint32_t save_n_idx;
  40.107 -	cell_t save_sp, save_hp;
  40.108 +	cell_t save_sp, save_hp, save_rp, save_cip;
  40.109  
  40.110  	save_sp = m_ctx.sp;
  40.111  	save_hp = m_ctx.hp;
  40.112  	save_exec = m_InExec;
  40.113  	save_n_idx = m_ctx.n_idx;
  40.114 +	save_rp = m_ctx.rp;
  40.115 +	save_cip = m_ctx.err_cip;
  40.116  
  40.117  	/* Push parameters */
  40.118  
  40.119 @@ -589,15 +644,11 @@
  40.120  	m_CustomMsg = false;
  40.121  	m_InExec = true;
  40.122  
  40.123 -	/* Start the tracer */
  40.124 -
  40.125 -	g_engine1.PushTracer(this);
  40.126 +	/* Start the frame tracer */
  40.127  
  40.128 -	/* Execute the function */
  40.129 +	ir = g_Jit.InvokeFunction(m_pRuntime, fn, result);
  40.130  
  40.131 -	ir = g_Jit1.ContextExecute(m_pPlugin, &m_ctx, pubfunc->code_offs, result);
  40.132 -
  40.133 -	/* Restore some states, stop tracing */
  40.134 +	/* Restore some states, stop the frame tracer */
  40.135  
  40.136  	m_InExec = save_exec;
  40.137  
  40.138 @@ -618,18 +669,30 @@
  40.139  				m_ctx.hp, 
  40.140  				save_hp);
  40.141  		}
  40.142 +		if (m_ctx.rp != save_rp)
  40.143 +		{
  40.144 +			ir = SP_ERROR_STACKLEAK;
  40.145 +			_SetErrorMessage("Return stack leak detected: rp:%d should be %d!",
  40.146 +				m_ctx.rp,
  40.147 +				save_rp);
  40.148 +		}
  40.149 +	}
  40.150 +
  40.151 +	if (ir != SP_ERROR_NONE)
  40.152 +	{
  40.153 +		g_engine1.ReportError(m_pRuntime, ir, m_MsgCache, save_rp);
  40.154  	}
  40.155  
  40.156  	m_ctx.sp = save_sp;
  40.157  	m_ctx.hp = save_hp;
  40.158 -
  40.159 -	g_engine1.PopTracer(ir, m_CustomMsg ? m_MsgCache : NULL);
  40.160 -
  40.161 +	m_ctx.rp = save_rp;
  40.162 +	
  40.163  	if ((m_pPlugin->prof_flags & SP_PROF_CALLBACKS) == SP_PROF_CALLBACKS)
  40.164  	{
  40.165  		m_pPlugin->profiler->OnCallbackEnd(serial);
  40.166  	}
  40.167  
  40.168 +	m_ctx.err_cip = save_cip;
  40.169  	m_ctx.n_idx = save_n_idx;
  40.170  	m_ctx.n_err = SP_ERROR_NONE;
  40.171  	m_MsgCache[0] = '\0';
  40.172 @@ -643,23 +706,6 @@
  40.173  	return m_pRuntime;
  40.174  }
  40.175  
  40.176 -int BaseRuntime::ApplyCompilationOptions(ICompilation *co)
  40.177 -{
  40.178 -	int err;
  40.179 -
  40.180 -	/* The JIT does not destroy anything until it is guaranteed to succeed. */
  40.181 -	if (!g_Jit1.Compile(co, this, &err))
  40.182 -	{
  40.183 -		return err;
  40.184 -	}
  40.185 -
  40.186 -	RefreshFunctionCache();
  40.187 -
  40.188 -	m_pCtx->Refresh();
  40.189 -
  40.190 -	return SP_ERROR_NONE;
  40.191 -}
  40.192 -
  40.193  DebugInfo::DebugInfo(sp_plugin_t *plugin) : m_pPlugin(plugin)
  40.194  {
  40.195  }
  40.196 @@ -676,7 +722,7 @@
  40.197  	while (high - low > 1)
  40.198  	{
  40.199  		mid = USHR(low + high);
  40.200 -		if (m_pPlugin->files[mid].addr <= addr)
  40.201 +		if (m_pPlugin->debug.files[mid].addr <= addr)
  40.202  		{
  40.203  			low = mid;
  40.204  		} else {
  40.205 @@ -689,33 +735,44 @@
  40.206  		return SP_ERROR_NOT_FOUND;
  40.207  	}
  40.208  
  40.209 -	*filename = m_pPlugin->files[low].name;
  40.210 +	*filename = m_pPlugin->debug.stringbase + m_pPlugin->debug.files[low].name;
  40.211  
  40.212  	return SP_ERROR_NONE;
  40.213  }
  40.214  
  40.215  int DebugInfo::LookupFunction(ucell_t addr, const char **name)
  40.216  {
  40.217 -	uint32_t iter, max = m_pPlugin->debug.syms_num;
  40.218 +	uint32_t max, iter;
  40.219 +	sp_fdbg_symbol_t *sym;
  40.220 +	sp_fdbg_arraydim_t *arr;
  40.221 +	uint8_t *cursor = (uint8_t *)(m_pPlugin->debug.symbols);
  40.222  
  40.223 -	for (iter=0; iter<max; iter++)
  40.224 +	max = m_pPlugin->debug.syms_num;
  40.225 +	for (iter = 0; iter < max; iter++)
  40.226  	{
  40.227 -		if ((m_pPlugin->symbols[iter].sym->ident == SP_SYM_FUNCTION) 
  40.228 -			&& (m_pPlugin->symbols[iter].codestart <= addr) 
  40.229 -			&& (m_pPlugin->symbols[iter].codeend > addr))
  40.230 +		sym = (sp_fdbg_symbol_t *)cursor;
  40.231 +
  40.232 +		if (sym->ident == SP_SYM_FUNCTION
  40.233 +			&& sym->codestart <= addr 
  40.234 +			&& sym->codeend > addr)
  40.235  		{
  40.236 -			break;
  40.237 +			*name = m_pPlugin->debug.stringbase + sym->name;
  40.238 +			return SP_ERROR_NONE;
  40.239  		}
  40.240 +
  40.241 +		if (sym->dimcount > 0)
  40.242 +		{
  40.243 +			cursor += sizeof(sp_fdbg_symbol_t);
  40.244 +			arr = (sp_fdbg_arraydim_t *)cursor;
  40.245 +			cursor += sizeof(sp_fdbg_arraydim_t) * sym->dimcount;
  40.246 +			continue;
  40.247 +		}
  40.248 +
  40.249 +		cursor += sizeof(sp_fdbg_symbol_t);
  40.250  	}
  40.251  
  40.252 -	if (iter >= max)
  40.253 -	{
  40.254 -		return SP_ERROR_NOT_FOUND;
  40.255 -	}
  40.256 +	return SP_ERROR_NOT_FOUND;
  40.257  
  40.258 -	*name = m_pPlugin->symbols[iter].name;
  40.259 -
  40.260 -	return SP_ERROR_NONE;
  40.261  }
  40.262  
  40.263  int DebugInfo::LookupLine(ucell_t addr, uint32_t *line)
  40.264 @@ -728,7 +785,7 @@
  40.265  	while (high - low > 1)
  40.266  	{
  40.267  		mid = USHR(low + high);
  40.268 -		if (m_pPlugin->lines[mid].addr <= addr)
  40.269 +		if (m_pPlugin->debug.lines[mid].addr <= addr)
  40.270  		{
  40.271  			low = mid;
  40.272  		} else {
  40.273 @@ -742,7 +799,7 @@
  40.274  	}
  40.275  
  40.276  	/* Since the CIP occurs BEFORE the line, we have to add one */
  40.277 -	*line = m_pPlugin->lines[low].line + 1;
  40.278 +	*line = m_pPlugin->debug.lines[low].line + 1;
  40.279  
  40.280  	return SP_ERROR_NONE;
  40.281  }
  40.282 @@ -781,30 +838,3 @@
  40.283  
  40.284  	return true;
  40.285  }
  40.286 -
  40.287 -void BaseContext::Refresh()
  40.288 -{
  40.289 -	/* Initialize the null references */
  40.290 -	uint32_t index;
  40.291 -	if (FindPubvarByName("NULL_VECTOR", &index) == SP_ERROR_NONE)
  40.292 -	{
  40.293 -		sp_pubvar_t *pubvar;
  40.294 -		GetPubvarByIndex(index, &pubvar);
  40.295 -		m_pNullVec = pubvar->offs;
  40.296 -	}
  40.297 -	else
  40.298 -	{
  40.299 -		m_pNullVec = NULL;
  40.300 -	}
  40.301 -
  40.302 -	if (FindPubvarByName("NULL_STRING", &index) == SP_ERROR_NONE)
  40.303 -	{
  40.304 -		sp_pubvar_t *pubvar;
  40.305 -		GetPubvarByIndex(index, &pubvar);
  40.306 -		m_pNullString = pubvar->offs;
  40.307 -	}
  40.308 -	else
  40.309 -	{
  40.310 -		m_pNullString = NULL;
  40.311 -	}
  40.312 -}
    41.1 --- a/sourcepawn/jit/sp_vm_engine.cpp	Sun Aug 10 05:39:25 2008 +0000
    41.2 +++ b/sourcepawn/jit/sp_vm_engine.cpp	Fri Aug 15 05:22:26 2008 +0000
    41.3 @@ -30,23 +30,18 @@
    41.4   */
    41.5  
    41.6  #include "sp_vm_types.h"
    41.7 -#include <sh_memory.h>
    41.8 -/* HACK to avoid including sourcehook.h for just the SH_ASSERT definition */
    41.9 -#if !defined  SH_ASSERT
   41.10 -	#define SH_ASSERT(x, info)
   41.11 -	#include <sh_pagealloc.h>
   41.12 -	#undef SH_ASSERT
   41.13 -#else
   41.14 -	#include <sh_pagealloc.h>
   41.15 -#endif
   41.16 -
   41.17  #include <malloc.h>
   41.18  #include <string.h>
   41.19  #include <assert.h>
   41.20 +#include <KeCodeAllocator.h>
   41.21  #include "sp_file_headers.h"
   41.22  #include "sp_vm_engine.h"
   41.23  #include "zlib/zlib.h"
   41.24  #include "sp_vm_basecontext.h"
   41.25 +#include "jit_x86.h"
   41.26 +#if defined __GNUC__
   41.27 +#include <unistd.h>
   41.28 +#endif
   41.29  
   41.30  SourcePawnEngine g_engine1;
   41.31  
   41.32 @@ -57,12 +52,8 @@
   41.33   #include <sys/mman.h>
   41.34  #endif
   41.35  
   41.36 -#define INVALID_CIP			0xFFFFFFFF
   41.37 -
   41.38  using namespace SourcePawn;
   41.39  
   41.40 -SourceHook::CPageAlloc g_ExeMemory(16);
   41.41 -
   41.42  #define ERROR_MESSAGE_MAX		25
   41.43  static const char *g_ErrorMsgTable[] = 
   41.44  {
   41.45 @@ -92,6 +83,8 @@
   41.46  	"Native detected error",
   41.47  	"Plugin not runnable",
   41.48  	"Call was aborted",
   41.49 +	"Plugin format is too old",
   41.50 +	"Plugin format is too new",
   41.51  };
   41.52  
   41.53  const char *SourcePawnEngine::GetErrorString(int error)
   41.54 @@ -107,33 +100,10 @@
   41.55  SourcePawnEngine::SourcePawnEngine()
   41.56  {
   41.57  	m_pDebugHook = NULL;
   41.58 -	m_CallStack = NULL;
   41.59 -	m_FreedCalls = NULL;
   41.60 -	m_CurChain = 0;
   41.61 -#if 0
   41.62 -	m_pFreeFuncs = NULL;
   41.63 -#endif
   41.64  }
   41.65  
   41.66  SourcePawnEngine::~SourcePawnEngine()
   41.67  {
   41.68 -	TracedCall *pTemp;
   41.69 -	while (m_FreedCalls)
   41.70 -	{
   41.71 -		pTemp = m_FreedCalls->next;
   41.72 -		delete m_FreedCalls;
   41.73 -		m_FreedCalls = pTemp;
   41.74 -	}
   41.75 -
   41.76 -#if 0
   41.77 -	CFunction *pNext;
   41.78 -	while (m_pFreeFuncs)
   41.79 -	{
   41.80 -		pNext = m_pFreeFuncs->m_pNext;
   41.81 -		delete m_pFreeFuncs;
   41.82 -		m_pFreeFuncs = pNext;
   41.83 -	}
   41.84 -#endif
   41.85  }
   41.86  
   41.87  void *SourcePawnEngine::ExecAlloc(size_t size)
   41.88 @@ -153,22 +123,22 @@
   41.89  
   41.90  void *SourcePawnEngine::AllocatePageMemory(size_t size)
   41.91  {
   41.92 -	return g_ExeMemory.Alloc(size);
   41.93 +	return g_Jit.AllocCode(size);
   41.94  }
   41.95  
   41.96  void SourcePawnEngine::SetReadExecute(void *ptr)
   41.97  {
   41.98 -	g_ExeMemory.SetRE(ptr);
   41.99 +	/* already re */
  41.100  }
  41.101  
  41.102  void SourcePawnEngine::SetReadWrite(void *ptr)
  41.103  {
  41.104 -	g_ExeMemory.SetRW(ptr);
  41.105 +	/* already rw */
  41.106  }
  41.107  
  41.108  void SourcePawnEngine::FreePageMemory(void *ptr)
  41.109  {
  41.110 -	g_ExeMemory.Free(ptr);
  41.111 +	g_Jit.FreeCode(ptr);
  41.112  }
  41.113  
  41.114  void SourcePawnEngine::ExecFree(void *address)
  41.115 @@ -180,6 +150,12 @@
  41.116  #endif
  41.117  }
  41.118  
  41.119 +void SourcePawnEngine::SetReadWriteExecute(void *ptr)
  41.120 +{
  41.121 +//:TODO:	g_ExeMemory.SetRWE(ptr);
  41.122 +	SetReadExecute(ptr);
  41.123 +}
  41.124 +
  41.125  void *SourcePawnEngine::BaseAlloc(size_t size)
  41.126  {
  41.127  	return malloc(size);
  41.128 @@ -224,142 +200,38 @@
  41.129  	return old;
  41.130  }
  41.131  
  41.132 -unsigned int SourcePawnEngine::GetContextCallCount()
  41.133 -{
  41.134 -	if (!m_CallStack)
  41.135 -	{
  41.136 -		return 0;
  41.137 -	}
  41.138 -
  41.139 -	return m_CallStack->chain;
  41.140 -}
  41.141 -
  41.142 -TracedCall *SourcePawnEngine::MakeTracedCall(bool new_chain)
  41.143 -{
  41.144 -	TracedCall *pCall;
  41.145 -
  41.146 -	if (!m_FreedCalls)
  41.147 -	{
  41.148 -		pCall = new TracedCall;
  41.149 -	} else {
  41.150 -		/* Unlink the head node from the free list */
  41.151 -		pCall = m_FreedCalls;
  41.152 -		m_FreedCalls = m_FreedCalls->next;
  41.153 -	}
  41.154 -
  41.155 -	/* Link as the head node into the call stack */
  41.156 -	pCall->next = m_CallStack;
  41.157 -
  41.158 -	if (new_chain)
  41.159 -	{
  41.160 -		pCall->chain = ++m_CurChain;
  41.161 -	} else {
  41.162 -		pCall->chain = m_CurChain;
  41.163 -	}
  41.164 -
  41.165 -	m_CallStack = pCall;
  41.166 -
  41.167 -	return pCall;
  41.168 -}
  41.169 -
  41.170 -void SourcePawnEngine::FreeTracedCall(TracedCall *pCall)
  41.171 -{
  41.172 -	/* Check if this is the top of the call stack */
  41.173 -	if (pCall == m_CallStack)
  41.174 -	{
  41.175 -		m_CallStack = m_CallStack->next;
  41.176 -	}
  41.177 -
  41.178 -	/* Add this to our linked list of freed calls */
  41.179 -	if (!m_FreedCalls)
  41.180 -	{
  41.181 -		m_FreedCalls = pCall;
  41.182 -		m_FreedCalls->next = NULL;
  41.183 -	} else {
  41.184 -		pCall->next = m_FreedCalls;
  41.185 -		m_FreedCalls = pCall;
  41.186 -	}
  41.187 -}
  41.188 -
  41.189 -void SourcePawnEngine::PushTracer(BaseContext *ctx)
  41.190 -{
  41.191 -	TracedCall *pCall = MakeTracedCall(true);
  41.192 -
  41.193 -	pCall->cip = INVALID_CIP;
  41.194 -	pCall->ctx = ctx;
  41.195 -	pCall->frm = INVALID_CIP;
  41.196 -}
  41.197 -
  41.198 -void SourcePawnEngine::RunTracer(BaseContext *ctx, uint32_t frame, uint32_t codeip)
  41.199 -{
  41.200 -	assert(m_CallStack != NULL);
  41.201 -	assert(m_CallStack->ctx == ctx);
  41.202 -	assert(m_CallStack->chain == m_CurChain);
  41.203 -
  41.204 -	if (m_CallStack->cip == INVALID_CIP)
  41.205 -	{
  41.206 -		/* We aren't logging anything yet, so begin the trace */
  41.207 -		m_CallStack->cip = codeip;
  41.208 -		m_CallStack->frm = frame;
  41.209 -	} else {
  41.210 -		if (m_CallStack->frm > frame)
  41.211 -		{
  41.212 -			/* The last frame has moved down the stack, 
  41.213 -			 * so we have to push a new call onto our list.
  41.214 -			 */
  41.215 -			TracedCall *pCall = MakeTracedCall(false);
  41.216 -			pCall->ctx = ctx;
  41.217 -			pCall->frm = frame;
  41.218 -		} else if (m_CallStack->frm < frame) {
  41.219 -			/* The last frame has moved up the stack,
  41.220 -			 * so we have to pop the call from our list.
  41.221 -			 */
  41.222 -			FreeTracedCall(m_CallStack);
  41.223 -		}
  41.224 -		/* no matter where we are, update the cip */
  41.225 -		m_CallStack->cip = codeip;
  41.226 -	}
  41.227 -}
  41.228 -
  41.229 -void SourcePawnEngine::PopTracer(int error, const char *msg)
  41.230 -{
  41.231 -	assert(m_CallStack != NULL);
  41.232 -
  41.233 -	if (error != SP_ERROR_NONE && m_pDebugHook)
  41.234 -	{
  41.235 -		uint32_t native = INVALID_CIP;
  41.236 -
  41.237 -		if (m_CallStack->ctx->GetCtx()->n_err)
  41.238 -		{
  41.239 -			native = m_CallStack->ctx->GetCtx()->n_idx;
  41.240 -		}
  41.241 -
  41.242 -		CContextTrace trace(m_CallStack, error, msg, native);
  41.243 -		m_pDebugHook->OnContextExecuteError(m_CallStack->ctx, &trace);
  41.244 -	}
  41.245 -
  41.246 -	/* Now pop the error chain  */
  41.247 -	while (m_CallStack && m_CallStack->chain == m_CurChain)
  41.248 -	{
  41.249 -		FreeTracedCall(m_CallStack);
  41.250 -	}
  41.251 -
  41.252 -	m_CurChain--;
  41.253 -}
  41.254 -
  41.255  unsigned int SourcePawnEngine::GetEngineAPIVersion()
  41.256  {
  41.257  	return SOURCEPAWN_ENGINE_API_VERSION;
  41.258  }
  41.259  
  41.260 -CContextTrace::CContextTrace(TracedCall *pStart, int error, const char *msg, uint32_t native) : 
  41.261 - m_Error(error), m_pMsg(msg), m_pStart(pStart), m_pIterator(pStart), m_Native(native)
  41.262 +unsigned int SourcePawnEngine::GetContextCallCount()
  41.263 +{
  41.264 +	return 0;
  41.265 +}
  41.266 +
  41.267 +void SourcePawnEngine::ReportError(BaseRuntime *runtime, int err, const char *errstr, cell_t rp_start)
  41.268  {
  41.269 +	if (m_pDebugHook == NULL)
  41.270 +	{
  41.271 +		return;
  41.272 +	}
  41.273 +
  41.274 +	CContextTrace trace(runtime, err, errstr, rp_start);
  41.275 +
  41.276 +	m_pDebugHook->OnContextExecuteError(runtime->GetDefaultContext(), &trace);
  41.277 +}
  41.278 +
  41.279 +CContextTrace::CContextTrace(BaseRuntime *pRuntime, int err, const char *errstr, cell_t start_rp) 
  41.280 +: m_pRuntime(pRuntime), m_Error(err), m_pMsg(errstr), m_StartRp(start_rp), m_Level(0)
  41.281 +{
  41.282 +	m_ctx = pRuntime->m_pCtx->GetCtx();
  41.283 +	m_pDebug = m_pRuntime->GetDebugInfo();
  41.284  }
  41.285  
  41.286  bool CContextTrace::DebugInfoAvailable()
  41.287  {
  41.288 -	return m_pStart->ctx->IsDebugging();
  41.289 +	return (m_pDebug != NULL);
  41.290  }
  41.291  
  41.292  const char *CContextTrace::GetCustomErrorString()
  41.293 @@ -374,83 +246,99 @@
  41.294  
  41.295  const char *CContextTrace::GetErrorString()
  41.296  {
  41.297 -	if (m_Error > ERROR_MESSAGE_MAX || 
  41.298 -		m_Error < 1)
  41.299 +	if (m_Error > ERROR_MESSAGE_MAX || m_Error < 1)
  41.300  	{
  41.301  		return "Invalid error code";
  41.302 -	} else {
  41.303 +	}
  41.304 +	else
  41.305 +	{
  41.306  		return g_ErrorMsgTable[m_Error];
  41.307  	}
  41.308  }
  41.309  
  41.310  void CContextTrace::ResetTrace()
  41.311  {
  41.312 -	m_pIterator = m_pStart;
  41.313 +	m_Level = 0;
  41.314  }
  41.315  
  41.316  bool CContextTrace::GetTraceInfo(CallStackInfo *trace)
  41.317  {
  41.318 -	if (!m_pIterator || (m_pIterator->chain != m_pStart->chain))
  41.319 +	cell_t cip;
  41.320 +
  41.321 +	if (m_Level == 0)
  41.322  	{
  41.323 -		return false;
  41.324 +		cip = m_ctx->err_cip;
  41.325  	}
  41.326 -
  41.327 -	if (m_pIterator->cip == INVALID_CIP)
  41.328 +	else if (m_ctx->rp > 0)
  41.329  	{
  41.330 -		return false;
  41.331 -	}
  41.332 +		/* Entries go from ctx.rp - 1 to m_StartRp */
  41.333 +		cell_t offs, start, end;
  41.334 +
  41.335 +		offs = m_Level - 1;
  41.336 +		start = m_ctx->rp - 1;
  41.337 +		end = m_StartRp;
  41.338  
  41.339 -	IPluginContext *pContext = m_pIterator->ctx;
  41.340 -	IPluginDebugInfo *pInfo = pContext->GetRuntime()->GetDebugInfo();
  41.341 +		if (start - offs < end)
  41.342 +		{
  41.343 +			return false;
  41.344 +		}
  41.345  
  41.346 -	if (!pInfo)
  41.347 +		cip = m_ctx->rstk_cips[start - offs];
  41.348 +	}
  41.349 +	else
  41.350  	{
  41.351  		return false;
  41.352  	}
  41.353  
  41.354 -	if (!trace)
  41.355 +	if (trace == NULL)
  41.356  	{
  41.357 -		m_pIterator = m_pIterator->next;
  41.358 +		m_Level++;
  41.359  		return true;
  41.360  	}
  41.361  
  41.362 -	if (pInfo->LookupFile(m_pIterator->cip, &(trace->filename)) != SP_ERROR_NONE)
  41.363 +	if (m_pDebug->LookupFile(cip, &(trace->filename)) != SP_ERROR_NONE)
  41.364  	{
  41.365  		trace->filename = NULL;
  41.366  	}
  41.367  
  41.368 -	if (pInfo->LookupFunction(m_pIterator->cip, &(trace->function)) != SP_ERROR_NONE)
  41.369 +	if (m_pDebug->LookupFunction(cip, &(trace->function)) != SP_ERROR_NONE)
  41.370  	{
  41.371  		trace->function = NULL;
  41.372  	}
  41.373  
  41.374 -	if (pInfo->LookupLine(m_pIterator->cip, &(trace->line)) != SP_ERROR_NONE)
  41.375 +	if (m_pDebug->LookupLine(cip, &(trace->line)) != SP_ERROR_NONE)
  41.376  	{
  41.377  		trace->line = 0;
  41.378  	}
  41.379  
  41.380 -	m_pIterator = m_pIterator->next;
  41.381 +	m_Level++;
  41.382  
  41.383  	return true;
  41.384  }
  41.385  
  41.386  const char *CContextTrace::GetLastNative(uint32_t *index)
  41.387  {
  41.388 -	if (m_Native == INVALID_CIP)
  41.389 +	if (m_ctx->n_err == SP_ERROR_NONE)
  41.390  	{
  41.391  		return NULL;
  41.392  	}
  41.393  
  41.394  	sp_native_t *native;
  41.395 -	if (m_pIterator->ctx->GetNativeByIndex(m_Native, &native) != SP_ERROR_NONE)
  41.396 +	if (m_pRuntime->GetNativeByIndex(m_ctx->n_idx, &native) != SP_ERROR_NONE)
  41.397  	{
  41.398  		return NULL;
  41.399  	}
  41.400  
  41.401  	if (index)
  41.402  	{
  41.403 -		*index = m_Native;
  41.404 +		*index = m_ctx->n_idx;
  41.405  	}
  41.406  
  41.407  	return native->name;
  41.408  }
  41.409 +
  41.410 +IDebugListener *SourcePawnEngine::GetDebugHook()
  41.411 +{
  41.412 +	return m_pDebugHook;
  41.413 +}
  41.414 +
    42.1 --- a/sourcepawn/jit/sp_vm_engine.h	Sun Aug 10 05:39:25 2008 +0000
    42.2 +++ b/sourcepawn/jit/sp_vm_engine.h	Fri Aug 15 05:22:26 2008 +0000
    42.3 @@ -37,19 +37,10 @@
    42.4  
    42.5  class BaseContext;
    42.6  
    42.7 -struct TracedCall
    42.8 -{
    42.9 -	uint32_t cip;
   42.10 -	uint32_t frm;
   42.11 -	BaseContext *ctx;
   42.12 -	TracedCall *next;
   42.13 -	unsigned int chain;
   42.14 -};
   42.15 -
   42.16  class CContextTrace : public IContextTrace
   42.17  {
   42.18  public:
   42.19 -	CContextTrace(TracedCall *pStart, int error, const char *msg, uint32_t native);
   42.20 +	CContextTrace(BaseRuntime *pRuntime, int err, const char *errstr, cell_t start_rp);
   42.21  public:
   42.22  	int GetErrorCode();
   42.23  	const char *GetErrorString();
   42.24 @@ -59,11 +50,13 @@
   42.25  	void ResetTrace();
   42.26  	const char *GetLastNative(uint32_t *index);
   42.27  private:
   42.28 +	BaseRuntime *m_pRuntime;
   42.29 +	sp_context_t *m_ctx;
   42.30  	int m_Error;
   42.31  	const char *m_pMsg;
   42.32 -	TracedCall *m_pStart;
   42.33 -	TracedCall *m_pIterator;
   42.34 -	uint32_t m_Native;
   42.35 +	cell_t m_StartRp;
   42.36 +	cell_t m_Level;
   42.37 +	IPluginDebugInfo *m_pDebug;
   42.38  };
   42.39  
   42.40  class SourcePawnEngine : public ISourcePawnEngine
   42.41 @@ -85,37 +78,16 @@
   42.42  	void *AllocatePageMemory(size_t size);
   42.43  	void SetReadWrite(void *ptr);
   42.44  	void SetReadExecute(void *ptr);
   42.45 +	void SetReadWriteExecute(void *ptr);
   42.46  	void FreePageMemory(void *ptr);
   42.47  	const char *GetErrorString(int err);
   42.48 -public: //Debugger Stuff
   42.49 -	/**
   42.50 -	 * @brief Pushes a context onto the top of the call tracer.
   42.51 -	 * 
   42.52 -	 * @param ctx		Plugin context.
   42.53 -	 */
   42.54 -	void PushTracer(BaseContext *ctx);
   42.55 -
   42.56 -	/**
   42.57 -	 * @brief Pops a plugin off the call tracer.
   42.58 -	 */
   42.59 -	void PopTracer(int error, const char *msg);
   42.60 -
   42.61 -	/**
   42.62 -	 * @brief Runs tracer from a debug break.
   42.63 -	 */
   42.64 -	void RunTracer(BaseContext *ctx, uint32_t frame, uint32_t codeip);
   42.65 +	void ReportError(BaseRuntime *runtime, int err, const char *errstr, cell_t rp_start);
   42.66  public: //Plugin function stuff
   42.67  	CFunction *GetFunctionFromPool(funcid_t f, IPluginContext  *plugin);
   42.68  	void ReleaseFunctionToPool(CFunction *func);
   42.69 -private:
   42.70 -	TracedCall *MakeTracedCall(bool new_chain);
   42.71 -	void FreeTracedCall(TracedCall *pCall);
   42.72 +	IDebugListener *GetDebugHook();
   42.73  private:
   42.74  	IDebugListener *m_pDebugHook;
   42.75 -	TracedCall *m_FreedCalls;
   42.76 -	TracedCall *m_CallStack;
   42.77 -	unsigned int m_CurChain;
   42.78 -	//CFunction *m_pFreeFuncs;
   42.79  };
   42.80  
   42.81  extern SourcePawnEngine g_engine1;
    43.1 --- a/sourcepawn/jit/sp_vm_function.cpp	Sun Aug 10 05:39:25 2008 +0000
    43.2 +++ b/sourcepawn/jit/sp_vm_function.cpp	Fri Aug 15 05:22:26 2008 +0000
    43.3 @@ -38,13 +38,11 @@
    43.4  * FUNCTION CALLING *
    43.5  ********************/
    43.6  
    43.7 -void CFunction::Set(uint32_t code_addr, BaseRuntime *runtime, funcid_t fnid, uint32_t pub_id)
    43.8 +void CFunction::Set(BaseRuntime *runtime, funcid_t fnid, uint32_t pub_id)
    43.9  {
   43.10 -	m_codeaddr = code_addr;
   43.11  	m_pRuntime = runtime;
   43.12  	m_curparam = 0;
   43.13  	m_errorstate = SP_ERROR_NONE;
   43.14 -	m_Invalid = false;
   43.15  	m_FnId = fnid;
   43.16  }
   43.17  
   43.18 @@ -68,10 +66,9 @@
   43.19  	return m_pRuntime->GetDefaultContext();
   43.20  }
   43.21  
   43.22 -CFunction::CFunction(uint32_t code_addr, BaseRuntime *runtime, funcid_t id, uint32_t pub_id) : 
   43.23 -	m_codeaddr(code_addr), m_curparam(0), m_errorstate(SP_ERROR_NONE), m_FnId(id)
   43.24 +CFunction::CFunction(BaseRuntime *runtime, funcid_t id, uint32_t pub_id) : 
   43.25 +	m_curparam(0), m_errorstate(SP_ERROR_NONE), m_FnId(id)
   43.26  {
   43.27 -	m_Invalid = false;
   43.28  	m_pRuntime = runtime;
   43.29  }
   43.30  
   43.31 @@ -347,9 +344,3 @@
   43.32  	return err;
   43.33  }
   43.34  
   43.35 -bool CFunction::IsInvalidated()
   43.36 -{
   43.37 -	return m_Invalid;
   43.38 -}
   43.39 -
   43.40 -
    44.1 --- a/sourcepawn/jit/sp_vm_function.h	Sun Aug 10 05:39:25 2008 +0000
    44.2 +++ b/sourcepawn/jit/sp_vm_function.h	Fri Aug 15 05:22:26 2008 +0000
    44.3 @@ -54,13 +54,13 @@
    44.4  };
    44.5  
    44.6  class CPlugin;
    44.7 +class JitFunction;
    44.8  
    44.9  class CFunction : public IPluginFunction
   44.10  {
   44.11  	friend class SourcePawnEngine;
   44.12  public:
   44.13 -	CFunction(uint32_t code_addr,
   44.14 -			  BaseRuntime *pRuntime, 
   44.15 +	CFunction(BaseRuntime *pRuntime, 
   44.16  			  funcid_t fnid,
   44.17  			  uint32_t pub_id);
   44.18  public:
   44.19 @@ -75,8 +75,6 @@
   44.20  	virtual void Cancel();
   44.21  	virtual int CallFunction(const cell_t *params, unsigned int num_params, cell_t *result);
   44.22  	virtual IPluginContext *GetParentContext();
   44.23 -	bool IsInvalidated();
   44.24 -	void Invalidate();
   44.25  	bool IsRunnable();
   44.26  	funcid_t GetFunctionID();
   44.27  	int Execute2(IPluginContext *ctx, cell_t *result);
   44.28 @@ -85,19 +83,16 @@
   44.29  		unsigned int num_params, 
   44.30  		cell_t *result);
   44.31  public:
   44.32 -	void Set(uint32_t code_addr, BaseRuntime *runtime, funcid_t fnid, uint32_t pub_id);
   44.33 +	void Set(BaseRuntime *runtime, funcid_t fnid, uint32_t pub_id);
   44.34  private:
   44.35  	int _PushString(const char *string, int sz_flags, int cp_flags, size_t len);
   44.36  	int SetError(int err);
   44.37  private:
   44.38 -	uint32_t m_codeaddr;
   44.39  	BaseRuntime *m_pRuntime;
   44.40  	cell_t m_params[SP_MAX_EXEC_PARAMS];
   44.41  	ParamInfo m_info[SP_MAX_EXEC_PARAMS];
   44.42  	unsigned int m_curparam;
   44.43  	int m_errorstate;
   44.44 -	CFunction *m_pNext;
   44.45 -	bool m_Invalid;
   44.46  	funcid_t m_FnId;
   44.47  };
   44.48  
    45.1 --- a/sourcepawn/jit/x86/jit_x86.cpp	Sun Aug 10 05:39:25 2008 +0000
    45.2 +++ b/sourcepawn/jit/x86/jit_x86.cpp	Fri Aug 15 05:22:26 2008 +0000
    45.3 @@ -41,11 +41,14 @@
    45.4  #include "../BaseRuntime.h"
    45.5  #include "../sp_vm_basecontext.h"
    45.6  
    45.7 +using namespace Knight;
    45.8 +
    45.9  #if defined USE_UNGEN_OPCODES
   45.10  #include "ungen_opcodes.h"
   45.11  #endif
   45.12  
   45.13 -JITX86 g_Jit1;
   45.14 +JITX86 g_Jit;
   45.15 +KeCodeCache *g_pCodeCache = NULL;
   45.16  ISourcePawnEngine *engine = &g_engine1;
   45.17  
   45.18  inline sp_plugin_t *GETPLUGIN(sp_context_t *ctx)
   45.19 @@ -271,8 +274,7 @@
   45.20  
   45.21  inline void WriteOp_Proc(JitWriter *jit)
   45.22  {
   45.23 -	CompData *co = (CompData *)jit->data;
   45.24 -
   45.25 +#if 0 /* :TODO: We no longer use this */
   45.26  	/* Specialized code to align this taking in account the function magic number */
   45.27  	jitoffs_t cur_offs = jit->get_outputpos();
   45.28  	jitoffs_t offset = ((cur_offs & 0xFFFFFFF8) + 8) - cur_offs;
   45.29 @@ -295,8 +297,8 @@
   45.30  	/* Now we have to backpatch our reloction offset! */
   45.31  	{
   45.32  		jitoffs_t offs = jit->get_inputpos() - sizeof(cell_t);
   45.33 -		jitcode_t rebase = ((CompData *)jit->data)->rebase;
   45.34 -		*(jitoffs_t *)((unsigned char  *)rebase + offs) = jit->get_outputpos();
   45.35 +		uint8_t *rebase = ((CompData *)jit->data)->rebase;
   45.36 +		*(jitoffs_t *)(rebase + offs) = jit->get_outputpos();
   45.37  	}
   45.38  
   45.39  	/* Lastly, if we're writing, keep track of the function count */
   45.40 @@ -304,6 +306,7 @@
   45.41  	{
   45.42  		co->func_idx++;
   45.43  	}
   45.44 +#endif
   45.45  
   45.46  	//push old frame on stack:
   45.47  	//mov ecx, [esi+frm]
   45.48 @@ -312,6 +315,7 @@
   45.49  	IA32_Mov_Reg_Rm(jit, AMX_REG_TMP, AMX_REG_INFO, MOD_MEM_REG);
   45.50  	IA32_Mov_Rm_Reg_Disp8(jit, AMX_REG_STK, AMX_REG_TMP, -4);
   45.51  	IA32_Sub_Rm_Imm8(jit, AMX_REG_STK, 8, MOD_REG);
   45.52 +
   45.53  	//save frame:
   45.54  	//mov ecx, edi			- get new frame
   45.55  	//mov ebx, edi			- store frame back
   45.56 @@ -1065,7 +1069,7 @@
   45.57  		IA32_Mov_Rm_Reg_Disp8(jit, AMX_REG_INFO, AMX_REG_ALT, AMX_INFO_HEAP);
   45.58  		IA32_Add_Reg_Rm(jit, AMX_REG_ALT, AMX_REG_DAT, MOD_REG);
   45.59  		IA32_Cmp_Reg_Rm(jit, AMX_REG_ALT, AMX_REG_STK, MOD_REG);
   45.60 -		IA32_Jump_Cond_Imm32_Abs(jit, CC_AE, ((CompData *)jit->data)->jit_error_heaplow);
   45.61 +		IA32_Jump_Cond_Imm32_Rel(jit, CC_AE, ((CompData *)jit->data)->jit_error_heaplow);
   45.62  
   45.63  		WriteOp_Tracker_Push_Reg(jit, REG_ECX);
   45.64  
   45.65 @@ -1104,7 +1108,7 @@
   45.66  			IA32_Mov_Reg_Imm32(jit, REG_EDX, 0);
   45.67  		}
   45.68  		jitoffs_t call = IA32_Call_Imm32(jit, 0);
   45.69 -		IA32_Write_Jump32(jit, call, ((CompData *)jit->data)->jit_genarray);
   45.70 +		IA32_Write_Jump32_Abs(jit, call, g_Jit.GetGenArrayIntrinsic());
   45.71  	}
   45.72  }
   45.73  
   45.74 @@ -1376,51 +1380,97 @@
   45.75  	cell_t offs;
   45.76  	jitoffs_t jmp;
   45.77  	CompData *data;
   45.78 -		
   45.79 +	uint32_t func_idx;
   45.80 +	
   45.81  	data = (CompData *)jit->data; 
   45.82  	offs = jit->read_cell();
   45.83  
   45.84 -	if ((data->profile & SP_PROF_FUNCTIONS) == SP_PROF_FUNCTIONS)
   45.85 +	/* Get the context + rp */
   45.86 +	//mov eax, [esi+ctx]
   45.87 +	//mov ecx, [eax+rp]
   45.88 +	IA32_Mov_Reg_Rm_Disp8(jit, REG_EAX, AMX_REG_INFO, AMX_INFO_CONTEXT);
   45.89 +	IA32_Mov_Reg_Rm_Disp8(jit, REG_ECX, REG_EAX, offsetof(sp_context_t, rp));
   45.90 +
   45.91 +	/* Check if the return stack is used up. */
   45.92 +	//cmp ecx, <max stack>
   45.93 +	//jae :stacklow
   45.94 +	IA32_Cmp_Rm_Imm32(jit, MOD_REG, REG_ECX, SP_MAX_RETURN_STACK);
   45.95 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_AE, data->jit_error_stacklow);
   45.96 +	
   45.97 +	/* Add us to the return stack */
   45.98 +	//mov [eax+ecx*4+cips], cip
   45.99 +	IA32_Mov_Rm_Imm32_SIB(jit,
  45.100 +		REG_EAX,
  45.101 +		(uint8_t *)(jit->inptr - 2) - data->plugin->pcode,
  45.102 +		offsetof(sp_context_t, rstk_cips),
  45.103 +		REG_ECX,
  45.104 +		SCALE4);
  45.105 +
  45.106 +	/* Increment the return stack pointer */
  45.107 +	//inc [eax+rp]
  45.108 +	if ((int)offsetof(sp_context_t, rp) >= SCHAR_MIN && (int)offsetof(sp_context_t, rp) <= SCHAR_MAX)
  45.109  	{
  45.110 -		const char *name;
  45.111 -
  45.112 -		/* Find the function name */
  45.113 -		if ((name = find_func_name(data->plugin, offs)) == NULL)
  45.114 -		{
  45.115 -			name = "unknown";
  45.116 -		}
  45.117 -
  45.118 -		//push name
  45.119 -		//push [esi+context] 
  45.120 -		//call ProfCallGate_Begin
  45.121 -		//add esp, 8
  45.122 -		IA32_Push_Imm32(jit, (jit_int32_t)(intptr_t)name);
  45.123 -		IA32_Push_Rm_Disp8(jit, AMX_REG_INFO, AMX_INFO_CONTEXT);
  45.124 -		jmp = IA32_Call_Imm32(jit, 0);
  45.125 -		IA32_Write_Jump32_Abs(jit, jmp, (void *)ProfCallGate_Begin);
  45.126 -		IA32_Add_Rm_Imm8(jit, REG_ESP, 8, MOD_REG);
  45.127 -
  45.128 -		//call <addr>
  45.129 -		//push eax
  45.130 -		jmp = IA32_Call_Imm32(jit, 0);
  45.131 -		IA32_Write_Jump32(jit, jmp, RelocLookup(jit, offs, false));
  45.132 -		IA32_Push_Reg(jit, REG_EAX);
  45.133 -
  45.134 -		//push [esi+context]
  45.135 -		//call ProfCallGate_End
  45.136 -		//add esp, 4
  45.137 -		//pop eax
  45.138 -		IA32_Push_Rm_Disp8(jit, AMX_REG_INFO, AMX_INFO_CONTEXT);
  45.139 -		jmp = IA32_Call_Imm32(jit, 0);
  45.140 -		IA32_Write_Jump32_Abs(jit, jmp, (void *)ProfCallGate_End);
  45.141 -		IA32_Add_Rm_Imm8(jit, REG_ESP, 4, MOD_REG);
  45.142 -		IA32_Pop_Reg(jit, REG_EAX);
  45.143 +		IA32_Inc_Rm_Disp8(jit, REG_EAX, offsetof(sp_context_t, rp));
  45.144  	}
  45.145  	else
  45.146  	{
  45.147 +		IA32_Inc_Rm_Disp32(jit, REG_EAX, offsetof(sp_context_t, rp));
  45.148 +	}
  45.149 +
  45.150 +	/* Store the CIP of the function we're about to call. */
  45.151 +	IA32_Mov_Rm_Imm32_Disp8(jit, AMX_REG_INFO, offs, AMX_INFO_CIP);
  45.152 +
  45.153 +	/* Call the function */
  45.154 +	func_idx = FuncLookup(data, offs);
  45.155 +
  45.156 +	/* We need to emit a delayed thunk instead. */
  45.157 +	if (func_idx == 0)
  45.158 +	{
  45.159 +		if (jit->outbase == NULL)
  45.160 +		{
  45.161 +			data->num_thunks++;
  45.162 +
  45.163 +			/* We still emit the call because we need consistent size counting */
  45.164 +			IA32_Call_Imm32(jit, 0);
  45.165 +		}
  45.166 +		else
  45.167 +		{
  45.168 +			call_thunk_t *thunk;
  45.169 +
  45.170 +			/* Find the thunk we're associated with */
  45.171 +			thunk = &data->thunks[data->num_thunks];
  45.172 +			data->num_thunks++;
  45.173 +
  45.174 +			/* Emit the call, save its target position.
  45.175 +			 * Save thunk info, then patch the target to the thunk.
  45.176 +			 */
  45.177 +			thunk->patch_addr = IA32_Call_Imm32(jit, 0);
  45.178 +			thunk->pcode_offs = offs;
  45.179 +			IA32_Write_Jump32(jit, thunk->patch_addr, thunk->thunk_addr);
  45.180 +		}
  45.181 +	}
  45.182 +	/* The function is already jitted.  We can emit a direct call. */
  45.183 +	else
  45.184 +	{
  45.185 +		JitFunction *fn;
  45.186 +
  45.187 +		fn = data->runtime->GetJittedFunction(func_idx);
  45.188  		jmp = IA32_Call_Imm32(jit, 0);
  45.189 -		IA32_Write_Jump32(jit, jmp, RelocLookup(jit, offs, false));
  45.190 +		IA32_Write_Jump32_Abs(jit, jmp, fn->GetEntryAddress());
  45.191  	}
  45.192 +
  45.193 +	/* Restore the last cip */
  45.194 +	//mov [esi+cip], <cip>
  45.195 +	IA32_Mov_Rm_Imm32_Disp8(jit, 
  45.196 +		AMX_REG_INFO, 
  45.197 +		(uint8_t *)(jit->inptr - 2) - data->plugin->pcode, 
  45.198 +		AMX_INFO_CIP);
  45.199 +
  45.200 +	/* Mark us as leaving the last frame. */ 
  45.201 +	//mov ecx, [esi+ctx] 
  45.202 +	//dec [ecx+rp] 
  45.203 +	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_TMP, AMX_REG_INFO, AMX_INFO_CONTEXT); 
  45.204 +	IA32_Dec_Rm_Disp8(jit, REG_ECX, offsetof(sp_context_t, rp));
  45.205  }
  45.206  
  45.207  inline void WriteOp_Bounds(JitWriter *jit)
  45.208 @@ -1435,7 +1485,7 @@
  45.209  	} else {
  45.210  		IA32_Cmp_Eax_Imm32(jit, val);
  45.211  	}
  45.212 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_A, ((CompData *)jit->data)->jit_error_bounds);
  45.213 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_A, ((CompData *)jit->data)->jit_error_bounds);
  45.214  }
  45.215  
  45.216  inline void WriteOp_Halt(JitWriter *jit)
  45.217 @@ -1453,32 +1503,27 @@
  45.218  	 */
  45.219  	jit->read_cell();
  45.220  
  45.221 -	CompData *data = (CompData *)jit->data;
  45.222 -	IA32_Jump_Imm32_Abs(jit, data->jit_return);
  45.223 +	IA32_Jump_Imm32_Abs(jit, g_Jit.GetReturnPoint());
  45.224  }
  45.225  
  45.226  inline void WriteOp_Break(JitWriter *jit)
  45.227  {
  45.228 -	CompData *data = (CompData *)jit->data;
  45.229 -	if (data->debug)
  45.230 -	{
  45.231 -		//jit->write_ubyte(IA32_INT3);
  45.232 -		//mov ecx, <cip>
  45.233 -		jitoffs_t wr = IA32_Mov_Reg_Imm32(jit, AMX_REG_TMP, 0);
  45.234 -		jitoffs_t save = jit->get_outputpos();
  45.235 -		jit->set_outputpos(wr);
  45.236 -		jit->write_uint32((uint32_t)(wr));
  45.237 -		jit->set_outputpos(save);
  45.238 -		wr = IA32_Call_Imm32(jit, 0);
  45.239 -		IA32_Write_Jump32(jit, wr, data->jit_break);
  45.240 -	}
  45.241 +	CompData *data;
  45.242 +
  45.243 +	data = (CompData *)jit->data;
  45.244 +
  45.245 +	//mov [esi+cip], <cip>
  45.246 +	IA32_Mov_Rm_Imm32_Disp8(jit, 
  45.247 +		AMX_REG_INFO, 
  45.248 +		(uint8_t *)(jit->inptr - 1) - data->plugin->pcode, 
  45.249 +		AMX_INFO_CIP);
  45.250  }
  45.251  
  45.252  inline void WriteOp_Jump(JitWriter *jit)
  45.253  {
  45.254  	//jmp <offs>
  45.255  	cell_t amx_offs = jit->read_cell();
  45.256 -	IA32_Jump_Imm32_Abs(jit, RelocLookup(jit, amx_offs, false));
  45.257 +	IA32_Jump_Imm32_Rel(jit, RelocLookup(jit, amx_offs, false));
  45.258  }
  45.259  
  45.260  inline void WriteOp_Jzer(JitWriter *jit)
  45.261 @@ -1487,7 +1532,7 @@
  45.262  	//jz <target>
  45.263  	cell_t target = jit->read_cell();
  45.264  	IA32_Test_Rm_Reg(jit, AMX_REG_PRI, AMX_REG_PRI, MOD_REG);
  45.265 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_Z, RelocLookup(jit, target, false));
  45.266 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_Z, RelocLookup(jit, target, false));
  45.267  }
  45.268  
  45.269  inline void WriteOp_Jnz(JitWriter *jit)
  45.270 @@ -1496,7 +1541,7 @@
  45.271  	//jnz <target>
  45.272  	cell_t target = jit->read_cell();
  45.273  	IA32_Test_Rm_Reg(jit, AMX_REG_PRI, AMX_REG_PRI, MOD_REG);
  45.274 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, RelocLookup(jit, target, false));
  45.275 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_NZ, RelocLookup(jit, target, false));
  45.276  }
  45.277  
  45.278  inline void WriteOp_Jeq(JitWriter *jit)
  45.279 @@ -1505,7 +1550,7 @@
  45.280  	//je <target>
  45.281  	cell_t target = jit->read_cell();
  45.282  	IA32_Cmp_Reg_Rm(jit, AMX_REG_PRI, AMX_REG_ALT, MOD_REG);
  45.283 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_E, RelocLookup(jit, target, false));
  45.284 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_E, RelocLookup(jit, target, false));
  45.285  }
  45.286  
  45.287  inline void WriteOp_Jneq(JitWriter *jit)
  45.288 @@ -1514,7 +1559,7 @@
  45.289  	//jne <target>
  45.290  	cell_t target = jit->read_cell();
  45.291  	IA32_Cmp_Reg_Rm(jit, AMX_REG_PRI, AMX_REG_ALT, MOD_REG);
  45.292 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_NE, RelocLookup(jit, target, false));
  45.293 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_NE, RelocLookup(jit, target, false));
  45.294  }
  45.295  
  45.296  inline void WriteOp_Jsless(JitWriter *jit)
  45.297 @@ -1523,7 +1568,7 @@
  45.298  	//jl <target>
  45.299  	cell_t target = jit->read_cell();
  45.300  	IA32_Cmp_Reg_Rm(jit, AMX_REG_PRI, AMX_REG_ALT, MOD_REG);
  45.301 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_L, RelocLookup(jit, target, false));
  45.302 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_L, RelocLookup(jit, target, false));
  45.303  }
  45.304  
  45.305  inline void WriteOp_Jsleq(JitWriter *jit)
  45.306 @@ -1532,7 +1577,7 @@
  45.307  	//jle <target>
  45.308  	cell_t target = jit->read_cell();
  45.309  	IA32_Cmp_Reg_Rm(jit, AMX_REG_PRI, AMX_REG_ALT, MOD_REG);
  45.310 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_LE, RelocLookup(jit, target, false));
  45.311 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_LE, RelocLookup(jit, target, false));
  45.312  }
  45.313  
  45.314  inline void WriteOp_JsGrtr(JitWriter *jit)
  45.315 @@ -1541,7 +1586,7 @@
  45.316  	//jg <target>
  45.317  	cell_t target = jit->read_cell();
  45.318  	IA32_Cmp_Reg_Rm(jit, AMX_REG_PRI, AMX_REG_ALT, MOD_REG);
  45.319 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_G, RelocLookup(jit, target, false));
  45.320 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_G, RelocLookup(jit, target, false));
  45.321  }
  45.322  
  45.323  inline void WriteOp_JsGeq(JitWriter *jit)
  45.324 @@ -1550,7 +1595,7 @@
  45.325  	//jge <target>
  45.326  	cell_t target = jit->read_cell();
  45.327  	IA32_Cmp_Reg_Rm(jit, AMX_REG_PRI, AMX_REG_ALT, MOD_REG);
  45.328 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_GE, RelocLookup(jit, target, false));
  45.329 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_GE, RelocLookup(jit, target, false));
  45.330  }
  45.331  
  45.332  inline void WriteOp_Switch(JitWriter *jit)
  45.333 @@ -1570,7 +1615,7 @@
  45.334  	{
  45.335  		/* Special treatment for 0 cases */
  45.336  		//jmp <default>
  45.337 -		IA32_Jump_Imm32_Abs(jit, RelocLookup(jit, *tbl, false));
  45.338 +		IA32_Jump_Imm32_Rel(jit, RelocLookup(jit, *tbl, false));
  45.339  	} else {
  45.340  		/* Check if the case layout is fully sequential */
  45.341  		casetbl *iter = (casetbl *)(tbl + 1);
  45.342 @@ -1615,7 +1660,7 @@
  45.343  			IA32_Cmp_Rm_Imm32(jit, MOD_REG, AMX_REG_TMP, high_bound);
  45.344  		}
  45.345  		//ja <default case>
  45.346 -		IA32_Jump_Cond_Imm32_Abs(jit, CC_A, RelocLookup(jit, *tbl, false));
  45.347 +		IA32_Jump_Cond_Imm32_Rel(jit, CC_A, RelocLookup(jit, *tbl, false));
  45.348  
  45.349  		/**
  45.350  		 * Now we've taken the default case out of the way, it's time to do the
  45.351 @@ -1662,10 +1707,10 @@
  45.352  				} else {
  45.353  					IA32_Cmp_Eax_Imm32(jit, cases[i].val);
  45.354  				}
  45.355 -				IA32_Jump_Cond_Imm32_Abs(jit, CC_E, RelocLookup(jit, cases[i].offs, false));
  45.356 +				IA32_Jump_Cond_Imm32_Rel(jit, CC_E, RelocLookup(jit, cases[i].offs, false));
  45.357  			}
  45.358  			/* After all this, jump to the default case! */
  45.359 -			IA32_Jump_Imm32_Abs(jit, RelocLookup(jit, *tbl, false));
  45.360 +			IA32_Jump_Imm32_Rel(jit, RelocLookup(jit, *tbl, false));
  45.361  		}
  45.362  	}
  45.363  }
  45.364 @@ -1687,7 +1732,7 @@
  45.365  	 */
  45.366  	cell_t native_index = jit->read_cell();
  45.367  
  45.368 -	if ((uint32_t)native_index >= ((CompData*)jit->data)->plugin->info.natives_num)
  45.369 +	if ((uint32_t)native_index >= ((CompData*)jit->data)->plugin->num_natives)
  45.370  	{
  45.371  		((CompData *)jit->data)->error_set = SP_ERROR_INSTRUCTION_PARAM;
  45.372  		return;
  45.373 @@ -1700,29 +1745,6 @@
  45.374  	IA32_Write_Jump32(jit, call, ((CompData *)jit->data)->jit_sysreq_c);
  45.375  }
  45.376  
  45.377 -inline void WriteOp_Sysreq_N_NoInline(JitWriter *jit)
  45.378 -{
  45.379 -	/* store the number of parameters on the stack, 
  45.380 -	 * and store the native index as well.
  45.381 -	 */
  45.382 -	cell_t native_index = jit->read_cell();
  45.383 -	cell_t num_params = jit->read_cell();
  45.384 -	
  45.385 -	if ((uint32_t)native_index >= ((CompData*)jit->data)->plugin->info.natives_num)
  45.386 -	{
  45.387 -		((CompData *)jit->data)->error_set = SP_ERROR_INSTRUCTION_PARAM;
  45.388 -		return;
  45.389 -	}
  45.390 -
  45.391 -	//mov eax, <num_params>
  45.392 -	//mov ecx, <native_index>
  45.393 -	IA32_Mov_Reg_Imm32(jit, REG_EAX, num_params);
  45.394 -	IA32_Mov_Reg_Imm32(jit, REG_ECX, native_index);
  45.395 -
  45.396 -	jitoffs_t call = IA32_Call_Imm32(jit, 0);
  45.397 -	IA32_Write_Jump32(jit, call, ((CompData *)jit->data)->jit_sysreq_n);
  45.398 -}
  45.399 -
  45.400  inline void WriteOp_Sysreq_N(JitWriter *jit)
  45.401  {
  45.402  	/* The big daddy of opcodes. */
  45.403 @@ -1730,7 +1752,7 @@
  45.404  	cell_t num_params = jit->read_cell();
  45.405  	CompData *data = (CompData *)jit->data;
  45.406  
  45.407 -	if ((uint32_t)native_index >= data->plugin->info.natives_num)
  45.408 +	if ((uint32_t)native_index >= data->plugin->num_natives)
  45.409  	{
  45.410  		data->error_set = SP_ERROR_INSTRUCTION_PARAM;
  45.411  		return;
  45.412 @@ -1788,27 +1810,13 @@
  45.413  	//call NativeCallback
  45.414  	IA32_Push_Reg(jit, REG_EAX);
  45.415  	jitoffs_t call = IA32_Call_Imm32(jit, 0);
  45.416 -	if (!data->debug)
  45.417 +	if ((data->profile & SP_PROF_NATIVES) == SP_PROF_NATIVES)
  45.418  	{
  45.419 -		if ((data->profile & SP_PROF_NATIVES) == SP_PROF_NATIVES)
  45.420 -		{
  45.421 -			IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback_Profile);
  45.422 -		}
  45.423 -		else
  45.424 -		{
  45.425 -			IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback);
  45.426 -		}
  45.427 +		IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback_Profile);
  45.428  	}
  45.429  	else
  45.430  	{
  45.431 -		if ((data->profile & SP_PROF_NATIVES) == SP_PROF_NATIVES)
  45.432 -		{
  45.433 -			IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback_Debug_Profile);
  45.434 -		}
  45.435 -		else
  45.436 -		{
  45.437 -			IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback_Debug);
  45.438 -		}
  45.439 +		IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback);
  45.440  	}
  45.441  	
  45.442  	/* check for errors */
  45.443 @@ -1817,7 +1825,7 @@
  45.444  	//jnz :error
  45.445  	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_TMP, AMX_REG_INFO, AMX_INFO_CONTEXT);
  45.446  	IA32_Cmp_Rm_Disp8_Imm8(jit, AMX_REG_TMP, offsetof(sp_context_t, n_err), 0);
  45.447 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, data->jit_extern_error);
  45.448 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_NZ, data->jit_extern_error);
  45.449  
  45.450  	/* restore what we damaged */
  45.451  	//mov esp, ebx
  45.452 @@ -1846,7 +1854,6 @@
  45.453  
  45.454  inline void WriteOp_Tracker_Push_C(JitWriter *jit)
  45.455  {
  45.456 -	CompData *data = (CompData *)jit->data;
  45.457  	cell_t val = jit->read_cell();
  45.458  
  45.459  	/* Save registers that may be damaged by the call */
  45.460 @@ -1868,7 +1875,7 @@
  45.461  	//cmp eax, 0
  45.462  	//jnz :error
  45.463  	IA32_Cmp_Rm_Imm8(jit, MOD_REG, REG_EAX, 0);
  45.464 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, data->jit_return);
  45.465 +	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, g_Jit.GetReturnPoint());
  45.466  
  45.467  	/* Restore */
  45.468  	//pop eax
  45.469 @@ -1893,8 +1900,6 @@
  45.470  
  45.471  inline void WriteOp_Tracker_Pop_SetHeap(JitWriter *jit)
  45.472  {
  45.473 -	CompData *data = (CompData *)jit->data;
  45.474 -
  45.475  	/* Save registers that may be damaged by the call */
  45.476  	//push eax
  45.477  	//push edx
  45.478 @@ -1914,7 +1919,7 @@
  45.479  	//cmp eax, 0
  45.480  	//jnz :error
  45.481  	IA32_Cmp_Rm_Imm8(jit, MOD_REG, REG_EAX, 0);
  45.482 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, data->jit_return);
  45.483 +	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, g_Jit.GetReturnPoint());
  45.484  
  45.485  	/* Restore */
  45.486  	//pop eax
  45.487 @@ -2241,8 +2246,6 @@
  45.488  
  45.489  inline void WriteOp_FloatCompare(JitWriter *jit)
  45.490  {
  45.491 -	CompData *data = (CompData *)jit->data;
  45.492 -
  45.493  	//fld [edi]
  45.494  	//fld [edi+4]
  45.495  	//fucomip st(0), st(1)
  45.496 @@ -2255,7 +2258,7 @@
  45.497  	IA32_Fld_Mem32(jit, AMX_REG_STK);
  45.498  	IA32_Fld_Mem32_Disp8(jit, AMX_REG_STK, 4);
  45.499  	IA32_Fucomip_ST0_FPUreg(jit, 1);
  45.500 -	IA32_Mov_Reg_Imm32(jit, AMX_REG_TMP, (jit_int32_t)jit->outbase + data->jit_rounding_table);
  45.501 +	IA32_Mov_Reg_Imm32(jit, AMX_REG_TMP, (jit_int32_t)g_Jit.GetRoundingTable());
  45.502  	IA32_CmovCC_Rm_Disp8(jit, AMX_REG_TMP, CC_Z, 4);
  45.503  	IA32_CmovCC_Rm_Disp8(jit, AMX_REG_TMP, CC_B, 8);
  45.504  	IA32_CmovCC_Rm(jit, AMX_REG_TMP, CC_A);
  45.505 @@ -2266,6 +2269,45 @@
  45.506  	IA32_Add_Rm_Imm8(jit, AMX_REG_STK, 8, MOD_REG);
  45.507  }
  45.508  
  45.509 +inline void WriteOp_EndProc(JitWriter *jit)
  45.510 +{
  45.511 +}
  45.512 +
  45.513 +void Write_CallThunk(JitWriter *jit, jitoffs_t jmploc, cell_t pcode_offs)
  45.514 +{
  45.515 +	CompData *data;
  45.516 +	jitoffs_t call;
  45.517 +
  45.518 +	data = (CompData *)jit->data;
  45.519 +
  45.520 +	//push <jmploc_addr>
  45.521 +	//push <pcode_offs>
  45.522 +	//push <runtime>
  45.523 +	//call CompileFromThunk
  45.524 +	//add esp, 4*3
  45.525 +	//test eax, eax
  45.526 +	//jz :error
  45.527 +	//call eax
  45.528 +	//ret
  45.529 +	IA32_Push_Imm32(jit, (jit_int32_t)(jit->outbase + jmploc));
  45.530 +	IA32_Push_Imm32(jit, pcode_offs);
  45.531 +	IA32_Push_Imm32(jit, (jit_int32_t)(data->runtime));
  45.532 +	call = IA32_Call_Imm32(jit, 0);
  45.533 +	IA32_Write_Jump32_Abs(jit, call, (void *)CompileThunk);
  45.534 +	IA32_Add_Rm_Imm32(jit, REG_ESP, 4*3, MOD_REG);
  45.535 +	IA32_Test_Rm_Reg(jit, REG_EAX, REG_EAX, MOD_REG);
  45.536 +	call = IA32_Jump_Cond_Imm8(jit, CC_Z, 0);
  45.537 +	IA32_Call_Reg(jit, REG_EAX);
  45.538 +	IA32_Return(jit);
  45.539 +
  45.540 +	/* We decrement the frame and store the target cip. */
  45.541 +	//:error
  45.542 +	//mov [esi+cip], pcode_offs
  45.543 +	//goto error
  45.544 +	IA32_Send_Jump8_Here(jit, call);
  45.545 +	Write_SetError(jit, SP_ERROR_INVALID_INSTRUCTION);
  45.546 +}
  45.547 +
  45.548  /*************************************************
  45.549   *************************************************
  45.550   * JIT PROPER ************************************
  45.551 @@ -2273,58 +2315,46 @@
  45.552   *************************************************
  45.553   *************************************************/
  45.554  
  45.555 +void *CompileThunk(BaseRuntime *runtime, cell_t pcode_offs, void *jmploc_addr)
  45.556 +{
  45.557 +	int err;
  45.558 +	JitFunction *fn;
  45.559 +	uint32_t func_idx;
  45.560 +	void *target_addr;
  45.561 +	
  45.562 +	if ((func_idx = FuncLookup((CompData *)runtime->m_pCo, pcode_offs)) == 0)
  45.563 +	{
  45.564 +		fn = g_Jit.CompileFunction(runtime, pcode_offs, &err);
  45.565 +	}
  45.566 +	else
  45.567 +	{
  45.568 +		fn = runtime->GetJittedFunction(func_idx);
  45.569 +
  45.570 +#if defined _DEBUG
  45.571 +		g_engine1.GetDebugHook()->OnDebugSpew("Patching thunk to %s::%s", runtime->m_pPlugin->name, find_func_name(runtime->m_pPlugin, pcode_offs));
  45.572 +#endif
  45.573 +
  45.574 +	}
  45.575 +
  45.576 +	if (fn == NULL)
  45.577 +	{
  45.578 +		return NULL;
  45.579 +	}
  45.580 +
  45.581 +	target_addr = fn->GetEntryAddress();
  45.582 +
  45.583 +	/* Right now, we always keep the code RWE */
  45.584 +	*(intptr_t *)((char *)jmploc_addr) = 
  45.585 +		intptr_t(target_addr) - (intptr_t(jmploc_addr) + 4);
  45.586 +
  45.587 +	return target_addr;
  45.588 +}
  45.589 +
  45.590  cell_t NativeCallback(sp_context_t *ctx, ucell_t native_idx, cell_t *params)
  45.591  {
  45.592  	sp_native_t *native;
  45.593 -	sp_plugin_t *plugin;
  45.594 -
  45.595 -	plugin = (sp_plugin_t *)ctx->vm[JITVARS_PLUGIN];
  45.596 -	
  45.597 -	native = &plugin->natives[native_idx];
  45.598 -
  45.599 -	ctx->n_idx = native_idx;
  45.600 -	
  45.601 -	/* Technically both aren't needed, I guess */
  45.602 -	if (native->status == SP_NATIVE_UNBOUND)
  45.603 -	{
  45.604 -		ctx->n_err = SP_ERROR_INVALID_NATIVE;
  45.605 -		return 0;
  45.606 -	}
  45.607 -
  45.608 -	return native->pfn(GET_CONTEXT(ctx), params);
  45.609 -}
  45.610 -
  45.611 -cell_t NativeCallback_Profile(sp_context_t *ctx, ucell_t native_idx, cell_t *params)
  45.612 -{
  45.613 -	cell_t val;
  45.614 -	sp_native_t *native;
  45.615 -	sp_plugin_t *plugin;
  45.616 -
  45.617 -	plugin = (sp_plugin_t *)ctx->vm[JITVARS_PLUGIN];
  45.618 -
  45.619 -	native = &plugin->natives[native_idx];
  45.620 -
  45.621 -	ctx->n_idx = native_idx;
  45.622 -
  45.623 -	/* Technically both aren't needed, I guess */
  45.624 -	if (native->status == SP_NATIVE_UNBOUND)
  45.625 -	{
  45.626 -		ctx->n_err = SP_ERROR_INVALID_NATIVE;
  45.627 -		return 0;
  45.628 -	}
  45.629 -
  45.630 -	plugin->profiler->OnNativeBegin(GET_CONTEXT(ctx), native);
  45.631 -	val = native->pfn(GET_CONTEXT(ctx), params);
  45.632 -	plugin->profiler->OnNativeEnd();
  45.633 -
  45.634 -	return val;
  45.635 -}
  45.636 -
  45.637 -cell_t NativeCallback_Debug(sp_context_t *ctx, ucell_t native_idx, cell_t *params)
  45.638 -{
  45.639  	cell_t save_sp = ctx->sp;
  45.640  	cell_t save_hp = ctx->hp;
  45.641 -
  45.642  	sp_plugin_t *pl = GETPLUGIN(ctx);
  45.643  
  45.644  	ctx->n_idx = native_idx;
  45.645 @@ -2347,7 +2377,15 @@
  45.646  		return 0;
  45.647  	}
  45.648  
  45.649 -	cell_t result = NativeCallback(ctx, native_idx, params);
  45.650 +	native = &pl->natives[native_idx];
  45.651 +
  45.652 +	if (native->status == SP_NATIVE_UNBOUND)
  45.653 +	{
  45.654 +		ctx->n_err = SP_ERROR_INVALID_NATIVE;
  45.655 +		return 0;
  45.656 +	}
  45.657 +
  45.658 +	cell_t result = native->pfn(GET_CONTEXT(ctx), params);
  45.659  
  45.660  	if (ctx->n_err != SP_ERROR_NONE)
  45.661  	{
  45.662 @@ -2368,57 +2406,19 @@
  45.663  	return result;
  45.664  }
  45.665  
  45.666 -cell_t NativeCallback_Debug_Profile(sp_context_t *ctx, ucell_t native_idx, cell_t *params)
  45.667 +cell_t NativeCallback_Profile(sp_context_t *ctx, ucell_t native_idx, cell_t *params)
  45.668  {
  45.669 -	cell_t save_sp = ctx->sp;
  45.670 -	cell_t save_hp = ctx->hp;
  45.671 -
  45.672 -	sp_plugin_t *pl = GETPLUGIN(ctx);
  45.673 -
  45.674 -	ctx->n_idx = native_idx;
  45.675 -
  45.676 -	if (ctx->hp < (cell_t)pl->data_size)
  45.677 -	{
  45.678 -		ctx->n_err = SP_ERROR_HEAPMIN;
  45.679 -		return 0;
  45.680 -	}
  45.681 -
  45.682 -	if (ctx->hp + STACK_MARGIN > ctx->sp)
  45.683 -	{
  45.684 -		ctx->n_err = SP_ERROR_STACKLOW;
  45.685 -		return 0;
  45.686 -	}
  45.687 -
  45.688 -	if ((uint32_t)ctx->sp >= pl->mem_size)
  45.689 -	{
  45.690 -		ctx->n_err = SP_ERROR_STACKMIN;
  45.691 -		return 0;
  45.692 -	}
  45.693 -
  45.694 -	cell_t result = NativeCallback_Profile(ctx, native_idx, params);
  45.695 -
  45.696 -	if (ctx->n_err != SP_ERROR_NONE)
  45.697 -	{
  45.698 -		return result;
  45.699 -	}
  45.700 -
  45.701 -	if (save_sp != ctx->sp)
  45.702 -	{
  45.703 -		ctx->n_err = SP_ERROR_STACKLEAK;
  45.704 -		return result;
  45.705 -	}
  45.706 -	else if (save_hp != ctx->hp)
  45.707 -	{
  45.708 -		ctx->n_err = SP_ERROR_HEAPLEAK;
  45.709 -		return result;
  45.710 -	}
  45.711 -
  45.712 -	return result;
  45.713 +	/* :TODO: */
  45.714 +	return NativeCallback(ctx, native_idx, params);
  45.715  }
  45.716  
  45.717 -static cell_t InvalidNative(IPluginContext *pCtx, const cell_t *params)
  45.718 +uint32_t FuncLookup(CompData *data, cell_t pcode_offs)
  45.719  {
  45.720 -	return pCtx->ThrowNativeErrorEx(SP_ERROR_INVALID_NATIVE, "Invalid native");
  45.721 +	/* Offset must always be 1)positive and 2)less than or equal to the codesize */
  45.722 +	assert(pcode_offs >= 0 && (uint32_t)pcode_offs <= data->plugin->pcode_size);
  45.723 +
  45.724 +	/* Do the lookup in the native dictionary. */
  45.725 +	return *(jitoffs_t *)(data->rebase + pcode_offs);
  45.726  }
  45.727  
  45.728  jitoffs_t RelocLookup(JitWriter *jit, cell_t pcode_offs, bool relative)
  45.729 @@ -2434,7 +2434,7 @@
  45.730  			pcode_offs += jit->get_inputpos();
  45.731  		}
  45.732  		/* Offset must always be 1)positive and 2)less than or equal to the codesize */
  45.733 -		assert(pcode_offs >= 0 && (uint32_t)pcode_offs <= data->codesize);
  45.734 +		assert(pcode_offs >= 0 && (uint32_t)pcode_offs <= data->plugin->pcode_size);
  45.735  		/* Do the lookup in the native dictionary. */
  45.736  		return *(jitoffs_t *)(data->rebase + pcode_offs);
  45.737  	}
  45.738 @@ -2469,130 +2469,144 @@
  45.739  	data->jit_error_heapmin = jit->get_outputpos();
  45.740  	Write_SetError(jit, SP_ERROR_HEAPMIN);
  45.741  
  45.742 -	data->jit_error_array_too_big = jit->get_outputpos();
  45.743 -	Write_SetError(jit, SP_ERROR_ARRAY_TOO_BIG);
  45.744 -
  45.745  	data->jit_extern_error = jit->get_outputpos();
  45.746  	Write_GetError(jit);
  45.747  }
  45.748  
  45.749 -bool JITX86::Compile(ICompilation *co, BaseRuntime *prt, int *err)
  45.750 +ICompilation *JITX86::ApplyOptions(ICompilation *_IN, ICompilation *_OUT)
  45.751  {
  45.752 -	CompData *data = (CompData *)co;
  45.753 -	sp_plugin_t *plugin = data->plugin;
  45.754 -
  45.755 -	if (data->plugin == NULL)
  45.756 +	if (_IN == NULL)
  45.757  	{
  45.758 -		if (data->debug && !(prt->m_pPlugin->flags & SP_FLAG_DEBUG))
  45.759 -		{
  45.760 -			if (err != NULL)
  45.761 -			{
  45.762 -				*err = SP_ERROR_NOTDEBUGGING;
  45.763 -			}
  45.764 -			co->Abort();
  45.765 -			return false;
  45.766 -		}
  45.767 -
  45.768 -		data->SetRuntime(prt);
  45.769 -		plugin = data->plugin;
  45.770 +		return _OUT;
  45.771  	}
  45.772  
  45.773 -	/* The first phase is to browse */
  45.774 -	uint8_t *code = plugin->pcode;
  45.775 -	uint8_t *end_cip = plugin->pcode + plugin->pcode_size;
  45.776 +	CompData *_in = (CompData * )_IN;
  45.777 +	CompData *_out = (CompData * )_OUT;
  45.778 +
  45.779 +	_in->inline_level = _out->inline_level;
  45.780 +	_in->profile = _out->profile;
  45.781 +
  45.782 +	_out->Abort();
  45.783 +
  45.784 +	return _in;
  45.785 +}
  45.786 +
  45.787 +JITX86::JITX86()
  45.788 +{
  45.789 +	m_pJitEntry = NULL;
  45.790 +	m_pJitReturn = NULL;
  45.791 +	m_RoundTable[0] = -1;
  45.792 +	m_RoundTable[1] = 0;
  45.793 +	m_RoundTable[2] = 1;
  45.794 +	m_pJitGenArray = NULL;
  45.795 +}
  45.796 +
  45.797 +bool JITX86::InitializeJIT()
  45.798 +{
  45.799 +	jitoffs_t offs;
  45.800 +	JitWriter writer, *jit;
  45.801 +
  45.802 +	g_pCodeCache = KE_CreateCodeCache();
  45.803 +
  45.804 +	jit = &writer;
  45.805 +	
  45.806 +	/* Build the genarray intrinsic */
  45.807 +	jit->outbase = NULL;
  45.808 +	jit->outptr = NULL;
  45.809 +	WriteIntrinsic_GenArray(jit);
  45.810 +	m_pJitGenArray = Knight::KE_AllocCode(g_pCodeCache, jit->get_outputpos());
  45.811 +	jit->outbase = (jitcode_t)m_pJitGenArray;
  45.812 +	jit->outptr = jit->outbase;
  45.813 +	WriteIntrinsic_GenArray(jit);
  45.814 +
  45.815 +	/* Build the entry point */
  45.816 +	writer = JitWriter();
  45.817 +	jit->outbase = NULL;
  45.818 +	jit->outptr = NULL;
  45.819 +	Write_Execute_Function(jit);
  45.820 +	m_pJitEntry = Knight::KE_AllocCode(g_pCodeCache, jit->get_outputpos());
  45.821 +	jit->outbase = (jitcode_t)m_pJitEntry;
  45.822 +	jit->outptr = jit->outbase;
  45.823 +	offs = Write_Execute_Function(jit);
  45.824 +	m_pJitReturn = (uint8_t *)m_pJitEntry + offs;
  45.825 +
  45.826 +	return true;
  45.827 +}
  45.828 +
  45.829 +void JITX86::ShutdownJIT()
  45.830 +{
  45.831 +	KE_DestroyCodeCache(g_pCodeCache);
  45.832 +}
  45.833 +
  45.834 +JitFunction *JITX86::CompileFunction(BaseRuntime *prt, cell_t pcode_offs, int *err)
  45.835 +{
  45.836 +	CompData *data = (CompData *)prt->m_pCo;
  45.837 +	sp_plugin_t *plugin = data->plugin;
  45.838 +
  45.839 +	uint8_t *code = plugin->pcode + pcode_offs;
  45.840 +	uint8_t *end_code = plugin->pcode + plugin->pcode_size;
  45.841 +
  45.842 +	assert(FuncLookup(data, pcode_offs) == 0);
  45.843 +
  45.844 +	if (code >= end_code || *(cell_t *)code != OP_PROC)
  45.845 +	{
  45.846 +		*err = SP_ERROR_INVALID_INSTRUCTION;
  45.847 +		return NULL;
  45.848 +	}
  45.849 +
  45.850 +#if defined _DEBUG
  45.851 +	g_engine1.GetDebugHook()->OnDebugSpew("Compiling function %s::%s", prt->m_pPlugin->name, find_func_name(prt->m_pPlugin, pcode_offs));
  45.852 +#endif
  45.853 +
  45.854 +	code += sizeof(cell_t);
  45.855 +
  45.856  	OPCODE op;
  45.857 -
  45.858 -	/*********************************************
  45.859 -	 * FIRST PASS (medium load): writer.outbase is NULL, getting size only
  45.860 -	 * SECOND PASS (heavy load!!): writer.outbase is valid and output is written
  45.861 -	 *********************************************/
  45.862 -
  45.863 -	JitWriter writer;
  45.864 -	JitWriter *jit = &writer;
  45.865 -	cell_t *endptr = (cell_t *)(end_cip);
  45.866 -	uint32_t codemem = 0;
  45.867 -
  45.868 -	/* Initial code is written "blank,"
  45.869 -	 * so we can check the exact memory usage.
  45.870 -	 */
  45.871 -	data->codesize = plugin->pcode_size;
  45.872 +	uint32_t code_size;
  45.873 +	cell_t *cip, *end_cip;
  45.874 +	JitWriter writer, *jit;
  45.875 +
  45.876 +	jit = &writer;
  45.877 +	cip = (cell_t *)code;
  45.878 +	end_cip = (cell_t *)end_code;
  45.879  	writer.data = data;
  45.880 -	writer.inbase = (cell_t *)code;
  45.881 +	writer.inbase = cip;
  45.882  	writer.outptr = NULL;
  45.883  	writer.outbase = NULL;
  45.884 -	/* Allocate relocation.  One extra cell for final CIP. */
  45.885 -	data->rebase = (jitcode_t)engine->BaseAlloc(plugin->pcode_size + sizeof(cell_t));
  45.886 -
  45.887 -	/* We will jump back here for second pass */
  45.888 +	data->cur_func = pcode_offs;
  45.889 +
  45.890  jit_rewind:
  45.891 -	/* Initialize pass vars */
  45.892 +	data->num_thunks = 0;
  45.893  	writer.inptr = writer.inbase;
  45.894 -	data->jit_verify_addr_eax = 0;
  45.895 -	data->jit_verify_addr_edx = 0;
  45.896 -
  45.897 -	/* Write the prologue of the JIT */
  45.898 -	data->jit_return = Write_Execute_Function(jit);
  45.899 -
  45.900 -	/* Write the SYSREQ.N opcode if we need to */
  45.901 -	if (!(data->inline_level & JIT_INLINE_NATIVES))
  45.902 -	{
  45.903 -		AlignMe(jit);
  45.904 -		data->jit_sysreq_n = jit->get_outputpos();
  45.905 -		WriteOp_Sysreq_N_Function(jit);
  45.906 -	}
  45.907 -
  45.908 -	/* Write the debug section if we need it */
  45.909 -	if (data->debug == true)
  45.910 -	{
  45.911 -		AlignMe(jit);
  45.912 -		data->jit_break = jit->get_outputpos();
  45.913 -		Write_BreakDebug(jit);
  45.914 -	}
  45.915 -
  45.916 -	/* Plugins compiled with -O0 will need this! */
  45.917 -	AlignMe(jit);
  45.918 -	data->jit_sysreq_c = jit->get_outputpos();
  45.919 -	WriteOp_Sysreq_C_Function(jit);
  45.920 -
  45.921 -	AlignMe(jit);
  45.922 -	data->jit_genarray = jit->get_outputpos();
  45.923 -	WriteIntrinsic_GenArray(jit);
  45.924 -
  45.925 -	/* Write error checking routines that are called to */
  45.926 -	if (!(data->inline_level & JIT_INLINE_ERRORCHECKS))
  45.927 -	{
  45.928 -		AlignMe(jit);
  45.929 -		data->jit_verify_addr_eax = jit->get_outputpos();
  45.930 -		Write_Check_VerifyAddr(jit, REG_EAX);
  45.931 -	
  45.932 -		AlignMe(jit);
  45.933 -		data->jit_verify_addr_edx = jit->get_outputpos();
  45.934 -		Write_Check_VerifyAddr(jit, REG_EDX);
  45.935 -	}
  45.936 -
  45.937 -	/* Write the rounding table for the float compare opcode */
  45.938 -	data->jit_rounding_table = jit->get_outputpos();
  45.939 -	Write_RoundingTable(jit);
  45.940 +
  45.941 +	WriteOp_Proc(jit);
  45.942  
  45.943  	/* Actual code generation! */
  45.944  	if (writer.outbase == NULL)
  45.945  	{
  45.946  		/* First Pass - find codesize and resolve relocation */
  45.947 -		jitoffs_t pcode_offs;
  45.948 +		jitoffs_t jpcode_offs;
  45.949  		jitoffs_t native_offs;
  45.950  
  45.951 -		for (; writer.inptr < endptr;)
  45.952 +		for (; writer.inptr < end_cip;)
  45.953  		{
  45.954 +			op = (OPCODE)writer.peek_cell();
  45.955 +
  45.956 +			/* If we hit another function, we must stop. */
  45.957 +			if (op == OP_PROC || op == OP_ENDPROC)
  45.958 +			{
  45.959 +				break;
  45.960 +			}
  45.961 +
  45.962  			/* Store the native offset into the rebase memory.
  45.963  			 * This large chunk of memory lets us do an instant lookup
  45.964  			 * based on an original pcode offset.
  45.965  			 */
  45.966 -			pcode_offs = (jitoffs_t)((uint8_t *)writer.inptr - code);
  45.967 +			jpcode_offs = (jitoffs_t)((uint8_t *)writer.inptr - plugin->pcode);
  45.968  			native_offs = jit->get_outputpos();
  45.969 -			*((jitoffs_t *)(data->rebase + pcode_offs)) = native_offs;
  45.970 -
  45.971 -			/* Now read the opcode and continue. */
  45.972 -			op = (OPCODE)writer.read_cell();
  45.973 +			*((jitoffs_t *)(data->rebase + jpcode_offs)) = native_offs;
  45.974 +
  45.975 +			/* Read past the opcode. */
  45.976 +			writer.read_cell();
  45.977  
  45.978  			/* Patch the floating point natives with our opcodes */
  45.979  			if (op == OP_SYSREQ_N)
  45.980 @@ -2619,209 +2633,108 @@
  45.981  			if (data->error_set != SP_ERROR_NONE)
  45.982  			{
  45.983  				*err = data->error_set;
  45.984 -				co->Abort();
  45.985 -				return false;
  45.986 +				return NULL;
  45.987  			}
  45.988  		}
  45.989 -		/* Write these last because error jumps should be unpredicted, and thus forward */
  45.990 +
  45.991 +		/* Write these last because error jumps should be predicted forwardly (not taken) */
  45.992  		WriteErrorRoutines(data, jit);
  45.993  
  45.994 +		/* Build thunk tables */
  45.995 +		if (data->num_thunks > data->max_thunks)
  45.996 +		{
  45.997 +			data->max_thunks = data->num_thunks;
  45.998 +			data->thunks = (call_thunk_t *)realloc(
  45.999 +				data->thunks,
 45.1000 +				data->max_thunks * sizeof(call_thunk_t));
 45.1001 +		}
 45.1002 +
 45.1003 +		/* Write the thunk offsets.
 45.1004 +		 * :TODO: we can emit all but one call to Write_CallThunk().
 45.1005 +		 */
 45.1006 +		for (unsigned int i = 0; i < data->num_thunks; i++)
 45.1007 +		{
 45.1008 +			data->thunks[i].thunk_addr = jit->get_outputpos();
 45.1009 +			Write_CallThunk(jit, 0, 0);
 45.1010 +		}
 45.1011 +
 45.1012 +		/**
 45.1013 +		 * I don't understand the purpose of this code.
 45.1014 +		 * Why do we want to know about the last opcode?
 45.1015 +		 * It should already have gotten written.
 45.1016 +		 */
 45.1017 +		#if 0
 45.1018  		/* Write the final CIP to the last position in the reloc array */
 45.1019  		pcode_offs = (jitoffs_t)((uint8_t *)writer.inptr - code);
 45.1020  		native_offs = jit->get_outputpos();
 45.1021  		*((jitoffs_t *)(data->rebase + pcode_offs)) = native_offs;
 45.1022 +		#endif
 45.1023  
 45.1024  		/* the total codesize is now known! */
 45.1025 -		codemem = writer.get_outputpos();
 45.1026 -		writer.outbase = (jitcode_t)engine->AllocatePageMemory(codemem);
 45.1027 -		engine->SetReadWrite(writer.outbase);
 45.1028 +		code_size = writer.get_outputpos();
 45.1029 +		writer.outbase = (jitcode_t)Knight::KE_AllocCode(g_pCodeCache, code_size);
 45.1030  		writer.outptr = writer.outbase;
 45.1031 -		/* go back for third pass */
 45.1032 +
 45.1033 +		/* go back for second pass */
 45.1034  		goto jit_rewind;
 45.1035  	}
 45.1036  	else
 45.1037  	{
 45.1038  		/*******
 45.1039 -		 * THIRD PASS - write opcode info
 45.1040 +		 * SECOND PASS - write opcode info
 45.1041  		 *******/
 45.1042 -		for (; writer.inptr < endptr;)
 45.1043 +		for (; writer.inptr < end_cip;)
 45.1044  		{
 45.1045  			op = (OPCODE)writer.read_cell();
 45.1046 +
 45.1047 +			/* If we hit another function, we must stop. */
 45.1048 +			if (op == OP_PROC || op == OP_ENDPROC)
 45.1049 +			{
 45.1050 +				break;
 45.1051 +			}
 45.1052 +
 45.1053  			switch (op)
 45.1054  			{
 45.1055  				#include "opcode_switch.inc"
 45.1056  			}
 45.1057  		}
 45.1058 -		/* Write these last because error jumps should be unpredicted, and thus forward */
 45.1059 +
 45.1060 +		/* Write these last because error jumps should be predicted as not taken (forward) */
 45.1061  		WriteErrorRoutines(data, jit);
 45.1062  
 45.1063 -		engine->SetReadExecute(writer.outbase);
 45.1064 -	}
 45.1065 -
 45.1066 -	/*************
 45.1067 -	 * FOURTH PASS - Context Setup
 45.1068 -	 *************/
 45.1069 -
 45.1070 -	/* setup  basics */
 45.1071 -	sp_context_t *ctx = data->runtime->GetBaseContext()->GetCtx();
 45.1072 -
 45.1073 -	/* Clear out any old cruft */
 45.1074 -	if (plugin->codebase != NULL)
 45.1075 -	{
 45.1076 -		FreePluginVars(data->runtime->m_pPlugin);
 45.1077 -		FreeContextVars(ctx);
 45.1078 -	}
 45.1079 -	
 45.1080 -	plugin->codebase = writer.outbase;
 45.1081 -	plugin->jit_codesize = codemem;
 45.1082 -	plugin->jit_memsize = 0;
 45.1083 -
 45.1084 -	/* setup memory */
 45.1085 -
 45.1086 -	ctx->hp = plugin->data_size;
 45.1087 -	ctx->sp = plugin->mem_size - sizeof(cell_t);
 45.1088 -	ctx->frm = ctx->sp;
 45.1089 -	ctx->n_err = SP_ERROR_NONE;
 45.1090 -	ctx->n_idx = SP_ERROR_NONE;
 45.1091 -	plugin->prof_flags = data->profile;
 45.1092 -	plugin->run_flags = data->debug ? SPFLAG_PLUGIN_DEBUG : 0;
 45.1093 -
 45.1094 -	const char *strbase = plugin->info.stringbase;
 45.1095 -	uint32_t max, iter;
 45.1096 -
 45.1097 -	/* relocate public info */
 45.1098 -	if ((max = plugin->info.publics_num))
 45.1099 -	{
 45.1100 -		plugin->publics = new sp_public_t[max];
 45.1101 -		plugin->jit_memsize += sizeof(sp_public_t) * max;
 45.1102 -		for (iter=0; iter<max; iter++)
 45.1103 +		/* Write the thunk offsets. */
 45.1104 +		for (unsigned int i = 0; i < data->num_thunks; i++)
 45.1105  		{
 45.1106 -			plugin->publics[iter].name = strbase + plugin->info.publics[iter].name;
 45.1107 -			plugin->publics[iter].code_offs = RelocLookup(jit, plugin->info.publics[iter].address, false);
 45.1108 -			/* Encode the ID as a straight code offset */
 45.1109 -			plugin->publics[iter].funcid = (plugin->publics[iter].code_offs << 1);
 45.1110 -		}
 45.1111 -	}
 45.1112 -
 45.1113 -	/* relocate pubvar info */
 45.1114 -	if ((max = plugin->info.pubvars_num))
 45.1115 -	{
 45.1116 -		uint8_t *dat = plugin->memory;
 45.1117 -		plugin->pubvars = new sp_pubvar_t[max];
 45.1118 -		plugin->jit_memsize += sizeof(sp_pubvar_t) * max;
 45.1119 -		for (iter=0; iter<max; iter++)
 45.1120 -		{
 45.1121 -			plugin->pubvars[iter].name = strbase + plugin->info.pubvars[iter].name;
 45.1122 -			plugin->pubvars[iter].offs = (cell_t *)(dat + plugin->info.pubvars[iter].address);
 45.1123 -		}
 45.1124 -	}
 45.1125 -
 45.1126 -	/* relocate native info */
 45.1127 -	if ((max = plugin->info.natives_num)
 45.1128 -		&& plugin->natives == NULL)
 45.1129 -	{
 45.1130 -		plugin->natives = new sp_native_t[max];
 45.1131 -		plugin->jit_memsize += sizeof(sp_native_t) * max;
 45.1132 -		for (iter=0; iter<max; iter++)
 45.1133 -		{
 45.1134 -			plugin->natives[iter].name = strbase + plugin->info.natives[iter].name;
 45.1135 -			plugin->natives[iter].pfn = &InvalidNative;
 45.1136 -			plugin->natives[iter].status = SP_NATIVE_UNBOUND;
 45.1137 -			plugin->natives[iter].flags = 0;
 45.1138 -			plugin->natives[iter].user = NULL;
 45.1139 +			Write_CallThunk(jit, data->thunks[i].patch_addr, data->thunks[i].pcode_offs);
 45.1140  		}
 45.1141  	}
 45.1142  
 45.1143 -	/**
 45.1144 -	 * If we're debugging, make sure we copy the necessary info.
 45.1145 -	 */
 45.1146 -	if (data->debug)
 45.1147 -	{
 45.1148 -		strbase = plugin->debug.stringbase;
 45.1149 -		
 45.1150 -		/* relocate files */
 45.1151 -		max = plugin->debug.files_num;
 45.1152 -		plugin->files = new sp_debug_file_t[max];
 45.1153 -		plugin->jit_memsize += sizeof(sp_debug_file_t) * max;
 45.1154 -		for (iter=0; iter<max; iter++)
 45.1155 -		{
 45.1156 -			plugin->files[iter].addr = RelocLookup(jit, plugin->debug.files[iter].addr, false);
 45.1157 -			plugin->files[iter].name = strbase + plugin->debug.files[iter].name;
 45.1158 -		}
 45.1159 -
 45.1160 -		/* relocate lines */
 45.1161 -		max = plugin->debug.lines_num;
 45.1162 -		plugin->lines = new sp_debug_line_t[max];
 45.1163 -		plugin->jit_memsize += sizeof(sp_debug_line_t) * max;
 45.1164 -		for (iter=0; iter<max; iter++)
 45.1165 -		{
 45.1166 -			plugin->lines[iter].addr = RelocLookup(jit, plugin->debug.lines[iter].addr, false);
 45.1167 -			plugin->lines[iter].line = plugin->debug.lines[iter].line;
 45.1168 -		}
 45.1169 -
 45.1170 -		/* relocate arrays */
 45.1171 -		sp_fdbg_symbol_t *sym;
 45.1172 -		sp_fdbg_arraydim_t *arr;
 45.1173 -		uint8_t *cursor = (uint8_t *)(plugin->debug.symbols);
 45.1174 -		
 45.1175 -		max = plugin->debug.syms_num;
 45.1176 -		plugin->symbols = new sp_debug_symbol_t[max];
 45.1177 -		plugin->jit_memsize += sizeof(sp_debug_symbol_t) * max;
 45.1178 -		for (iter=0; iter<max; iter++)
 45.1179 -		{
 45.1180 -			sym = (sp_fdbg_symbol_t *)cursor;
 45.1181 -
 45.1182 -			/**
 45.1183 -			 * @brief There is an "issue" where the compiler will give totally bogus code 
 45.1184 -			 * address because codegeneration is still being calculated.  A simple fix for 
 45.1185 -			 * this is to coerce the codestart value to 0 when it's invalid.
 45.1186 -			 */
 45.1187 -			if (sym->codestart > data->codesize)
 45.1188 -			{
 45.1189 -				plugin->symbols[iter].codestart = 0;
 45.1190 -			} else {
 45.1191 -				plugin->symbols[iter].codestart = RelocLookup(jit, sym->codestart, false);
 45.1192 -			}
 45.1193 -			if (sym->codeend > data->codesize)
 45.1194 -			{
 45.1195 -				plugin->symbols[iter].codeend = data->codesize;
 45.1196 -			} else {
 45.1197 -				plugin->symbols[iter].codeend = RelocLookup(jit, sym->codeend, false);
 45.1198 -			}
 45.1199 -			plugin->symbols[iter].name = strbase + sym->name;
 45.1200 -			plugin->symbols[iter].sym = sym;
 45.1201 -
 45.1202 -			if (sym->dimcount > 0)
 45.1203 -			{
 45.1204 -				cursor += sizeof(sp_fdbg_symbol_t);
 45.1205 -				arr = (sp_fdbg_arraydim_t *)cursor;
 45.1206 -				plugin->symbols[iter].dims = arr;
 45.1207 -				cursor += sizeof(sp_fdbg_arraydim_t) * sym->dimcount;
 45.1208 -				continue;
 45.1209 -			}
 45.1210 -
 45.1211 -			plugin->symbols[iter].dims = NULL;
 45.1212 -			cursor += sizeof(sp_fdbg_symbol_t);
 45.1213 -		}
 45.1214 -	}
 45.1215 -
 45.1216 +	plugin->prof_flags = data->profile;
 45.1217 +
 45.1218 +	*err = SP_ERROR_NONE;
 45.1219 +
 45.1220 +	JitFunction *fn;
 45.1221 +	uint32_t func_idx;
 45.1222 +	
 45.1223 +	fn = new JitFunction(writer.outbase, pcode_offs);
 45.1224 +	func_idx = prt->AddJittedFunction(fn);
 45.1225 +	*(cell_t *)(data->rebase + pcode_offs) = func_idx;
 45.1226 +
 45.1227 +	return fn;
 45.1228 +}
 45.1229 +
 45.1230 +void JITX86::SetupContextVars(BaseRuntime *runtime, BaseContext *pCtx, sp_context_t *ctx)
 45.1231 +{
 45.1232  	tracker_t *trk = new tracker_t;
 45.1233 +
 45.1234  	ctx->vm[JITVARS_TRACKER] = trk;
 45.1235 -	ctx->vm[JITVARS_BASECTX] = data->runtime->GetDefaultContext();
 45.1236 +	ctx->vm[JITVARS_BASECTX] = pCtx; /* GetDefaultContext() is not constructed yet */
 45.1237  	ctx->vm[JITVARS_PROFILER] = g_engine2.GetProfiler();
 45.1238 -	ctx->vm[JITVARS_PLUGIN] = data->runtime->m_pPlugin;
 45.1239 +	ctx->vm[JITVARS_PLUGIN] = runtime->m_pPlugin;
 45.1240 +
 45.1241  	trk->pBase = (ucell_t *)malloc(1024);
 45.1242  	trk->pCur = trk->pBase;
 45.1243  	trk->size = 1024 / sizeof(cell_t);
 45.1244 -
 45.1245 -	plugin->jit_memsize += trk->size;
 45.1246 -
 45.1247 -	/* clean up relocation+compilation memory */
 45.1248 -	co->Abort();
 45.1249 -
 45.1250 -	*err = SP_ERROR_NONE;
 45.1251 -
 45.1252 -	return true;
 45.1253  }
 45.1254  
 45.1255  SPVM_NATIVE_FUNC JITX86::CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData)
 45.1256 @@ -2876,32 +2789,22 @@
 45.1257  	if (jw.outbase == NULL)
 45.1258  	{
 45.1259  		/* Second pass: Actually write */
 45.1260 -		jw.outbase = (jitcode_t)engine->AllocatePageMemory(jw.get_outputpos());
 45.1261 +		jw.outbase = (jitcode_t)KE_AllocCode(g_pCodeCache, jw.get_outputpos());
 45.1262  		if (!jw.outbase)
 45.1263  		{
 45.1264  			return NULL;
 45.1265  		}
 45.1266 -		engine->SetReadWrite(jw.outbase);
 45.1267  		jw.outptr = jw.outbase;
 45.1268  	
 45.1269  		goto rewind;
 45.1270  	}
 45.1271  
 45.1272 -	engine->SetReadExecute(jw.outbase);
 45.1273 -
 45.1274  	return (SPVM_NATIVE_FUNC)jw.outbase;
 45.1275  }
 45.1276  
 45.1277  void JITX86::DestroyFakeNative(SPVM_NATIVE_FUNC func)
 45.1278  {
 45.1279 -	engine->FreePageMemory((void *)func);
 45.1280 -}
 45.1281 -
 45.1282 -int JITX86::ContextExecute(sp_plugin_t *pl, sp_context_t *ctx, uint32_t code_idx, cell_t *result)
 45.1283 -{
 45.1284 -	typedef int (*CONTEXT_EXECUTE)(sp_context_t *, uint32_t, cell_t *);
 45.1285 - 	CONTEXT_EXECUTE fn = (CONTEXT_EXECUTE)pl->codebase;
 45.1286 -	return fn(ctx, code_idx, result);
 45.1287 +	KE_FreeCode(g_pCodeCache, (void *)func);
 45.1288  }
 45.1289  
 45.1290  ICompilation *JITX86::StartCompilation()
 45.1291 @@ -2917,10 +2820,10 @@
 45.1292  {
 45.1293  	plugin = runtime->m_pPlugin;
 45.1294  
 45.1295 -	uint32_t max_natives = plugin->info.natives_num;
 45.1296 -	const char *strbase = plugin->info.stringbase;
 45.1297 +	uint32_t max_natives = plugin->num_natives;
 45.1298  
 45.1299  	this->runtime = runtime;
 45.1300 +	this->plugin = runtime->m_pPlugin;
 45.1301  
 45.1302  	inline_level = JIT_INLINE_ERRORCHECKS|JIT_INLINE_NATIVES;
 45.1303  	error_set = SP_ERROR_NONE;
 45.1304 @@ -2928,43 +2831,69 @@
 45.1305  	jit_float_table = new floattbl_t[max_natives];
 45.1306  	for (uint32_t i=0; i<max_natives; i++)
 45.1307  	{
 45.1308 -		const char *name = strbase + plugin->info.natives[i].name;
 45.1309 +		const char *name = plugin->natives[i].name;
 45.1310  		if (!strcmp(name, "FloatAbs"))
 45.1311  		{
 45.1312  			jit_float_table[i].found = true;
 45.1313  			jit_float_table[i].index = OP_FABS;
 45.1314 -		} else if (!strcmp(name, "FloatAdd")) {
 45.1315 +		} 
 45.1316 +		else if (!strcmp(name, "FloatAdd")) 
 45.1317 +		{
 45.1318  			jit_float_table[i].found = true;
 45.1319  			jit_float_table[i].index = OP_FLOATADD;
 45.1320 -		} else if (!strcmp(name, "FloatSub")) {
 45.1321 +		} 
 45.1322 +		else if (!strcmp(name, "FloatSub")) 
 45.1323 +		{
 45.1324  			jit_float_table[i].found = true;
 45.1325  			jit_float_table[i].index = OP_FLOATSUB;
 45.1326 -		} else if (!strcmp(name, "FloatMul")) {
 45.1327 +		} 
 45.1328 +		else if (!strcmp(name, "FloatMul")) 
 45.1329 +		{
 45.1330  			jit_float_table[i].found = true;
 45.1331  			jit_float_table[i].index = OP_FLOATMUL;
 45.1332 -		} else if (!strcmp(name, "FloatDiv")) {
 45.1333 +		} 
 45.1334 +		else if (!strcmp(name, "FloatDiv")) 
 45.1335 +		{
 45.1336  			jit_float_table[i].found = true;
 45.1337  			jit_float_table[i].index = OP_FLOATDIV;
 45.1338 -		} else if (!strcmp(name, "float")) {
 45.1339 +		} 
 45.1340 +		else if (!strcmp(name, "float")) 
 45.1341 +		{
 45.1342  			jit_float_table[i].found = true;
 45.1343  			jit_float_table[i].index = OP_FLOAT;
 45.1344 -		} else if (!strcmp(name, "FloatCompare")) {
 45.1345 +		} 
 45.1346 +		else if (!strcmp(name, "FloatCompare")) 
 45.1347 +		{
 45.1348  			jit_float_table[i].found = true;
 45.1349  			jit_float_table[i].index = OP_FLOATCMP;
 45.1350 -		} else if (!strcmp(name, "RoundToZero")) {
 45.1351 +		} 
 45.1352 +		else if (!strcmp(name, "RoundToZero")) 
 45.1353 +		{
 45.1354  			jit_float_table[i].found = true;
 45.1355  			jit_float_table[i].index = OP_RND_TO_ZERO;
 45.1356 -		} else if (!strcmp(name, "RoundToCeil")) {
 45.1357 +		} 
 45.1358 +		else if (!strcmp(name, "RoundToCeil")) 
 45.1359 +		{
 45.1360  			jit_float_table[i].found = true;
 45.1361  			jit_float_table[i].index = OP_RND_TO_CEIL;
 45.1362 -		} else if (!strcmp(name, "RoundToFloor")) {
 45.1363 +		} 
 45.1364 +		else if (!strcmp(name, "RoundToFloor")) 
 45.1365 +		{
 45.1366  			jit_float_table[i].found = true;
 45.1367  			jit_float_table[i].index = OP_RND_TO_FLOOR;
 45.1368 -		} else if (!strcmp(name, "RoundToNearest")) {
 45.1369 +		} 
 45.1370 +		else if (!strcmp(name, "RoundToNearest")) 
 45.1371 +		{
 45.1372  			jit_float_table[i].found = true;
 45.1373  			jit_float_table[i].index = OP_RND_TO_NEAREST;
 45.1374  		}
 45.1375  	}
 45.1376 +
 45.1377 +	/* We need a relocation table.  This is the relocation table we'll use for jumps 
 45.1378 +	 * and calls alike.  One extra cell for final CIP.
 45.1379 +	 */
 45.1380 +	this->rebase = (uint8_t *)engine->BaseAlloc(plugin->pcode_size + sizeof(cell_t));
 45.1381 +	memset(this->rebase, 0, plugin->pcode_size + sizeof(cell_t));
 45.1382  }
 45.1383  
 45.1384  ICompilation *JITX86::StartCompilation(BaseRuntime *runtime)
 45.1385 @@ -2982,6 +2911,7 @@
 45.1386  	{
 45.1387  		engine->BaseFree(rebase);
 45.1388  	}
 45.1389 +	delete [] thunks;
 45.1390  	delete [] jit_float_table;
 45.1391  	delete this;
 45.1392  }
 45.1393 @@ -2992,42 +2922,10 @@
 45.1394  	delete (tracker_t *)ctx->vm[JITVARS_TRACKER];
 45.1395  }
 45.1396  
 45.1397 -void JITX86::FreePluginVars(sp_plugin_t *pl)
 45.1398 -{
 45.1399 -	delete [] pl->files;
 45.1400 -	delete [] pl->lines;
 45.1401 -	delete [] pl->publics;
 45.1402 -	delete [] pl->pubvars;
 45.1403 -	delete [] pl->symbols;
 45.1404 -
 45.1405 -	if (pl->codebase != NULL)
 45.1406 -	{
 45.1407 -		g_engine1.FreePageMemory(pl->codebase);
 45.1408 -		pl->codebase = NULL;
 45.1409 -	}
 45.1410 -
 45.1411 -	pl->files = NULL;
 45.1412 -	pl->lines = NULL;
 45.1413 -	pl->publics = NULL;
 45.1414 -	pl->pubvars = NULL;
 45.1415 -	pl->symbols = NULL;
 45.1416 -}
 45.1417 -
 45.1418  bool CompData::SetOption(const char *key, const char *val)
 45.1419  {
 45.1420  	if (strcmp(key, SP_JITCONF_DEBUG) == 0)
 45.1421  	{
 45.1422 -		if ((atoi(val) == 1) || !strcmp(val, "yes"))
 45.1423 -		{
 45.1424 -			debug = true;
 45.1425 -		} else {
 45.1426 -			debug = false;
 45.1427 -		}
 45.1428 -		if (debug && plugin && !(plugin->flags & SP_FLAG_DEBUG))
 45.1429 -		{
 45.1430 -			debug = false;
 45.1431 -			return false;
 45.1432 -		}
 45.1433  		return true;
 45.1434  	}
 45.1435  	else if (strcmp(key, SP_JITCONF_PROFILE) == 0)
 45.1436 @@ -3046,3 +2944,56 @@
 45.1437  	return false;
 45.1438  }
 45.1439  
 45.1440 +void *JITX86::GetGenArrayIntrinsic()
 45.1441 +{
 45.1442 +	return m_pJitGenArray;
 45.1443 +}
 45.1444 +
 45.1445 +void *JITX86::GetReturnPoint()
 45.1446 +{
 45.1447 +	return m_pJitReturn;
 45.1448 +}
 45.1449 +
 45.1450 +void *JITX86::GetRoundingTable()
 45.1451 +{
 45.1452 +	return m_RoundTable;
 45.1453 +}
 45.1454 +
 45.1455 +typedef int (*JIT_EXECUTE)(cell_t *vars, void *addr);
 45.1456 +int JITX86::InvokeFunction(BaseRuntime *runtime, JitFunction *fn, cell_t *result)
 45.1457 +{
 45.1458 +	int err;
 45.1459 +	JIT_EXECUTE pfn;
 45.1460 +	sp_context_t *ctx;
 45.1461 +	cell_t vars[AMX_NUM_INFO_VARS];
 45.1462 +
 45.1463 +	ctx = runtime->GetBaseContext()->GetCtx();
 45.1464 +
 45.1465 +	vars[0] = ctx->sp;
 45.1466 +	vars[1] = ctx->hp;
 45.1467 +	vars[2] = (cell_t)result;
 45.1468 +	vars[3] = (cell_t)ctx;
 45.1469 +	vars[4] = (cell_t)(runtime->m_pPlugin->memory + runtime->m_pPlugin->mem_size);
 45.1470 +	vars[5] = fn->GetPCodeAddress();
 45.1471 +	vars[6] = runtime->m_pPlugin->data_size;
 45.1472 +	vars[7] = (cell_t)(runtime->m_pPlugin->memory);
 45.1473 +	/* vars[8] will be set to ESP */
 45.1474 +
 45.1475 +	pfn = (JIT_EXECUTE)m_pJitEntry;
 45.1476 +	err = pfn(vars, fn->GetEntryAddress());
 45.1477 +
 45.1478 +	ctx->hp = vars[1];
 45.1479 +	ctx->err_cip = vars[5];
 45.1480 +
 45.1481 +	return err;
 45.1482 +}
 45.1483 +
 45.1484 +void *JITX86::AllocCode(size_t size)
 45.1485 +{
 45.1486 +	return Knight::KE_AllocCode(g_pCodeCache, size);
 45.1487 +}
 45.1488 +
 45.1489 +void JITX86::FreeCode(void *code)
 45.1490 +{
 45.1491 +	KE_FreeCode(g_pCodeCache, code);
 45.1492 +}
    46.1 --- a/sourcepawn/jit/x86/jit_x86.h	Sun Aug 10 05:39:25 2008 +0000
    46.2 +++ b/sourcepawn/jit/x86/jit_x86.h	Fri Aug 15 05:22:26 2008 +0000
    46.3 @@ -34,9 +34,11 @@
    46.4  
    46.5  #include <sp_vm_types.h>
    46.6  #include <sp_vm_api.h>
    46.7 -#include <jit_helpers.h>
    46.8 -#include "../jit_shared.h"
    46.9 -#include "../BaseRuntime.h"
   46.10 +#include <KeCodeAllocator.h>
   46.11 +#include "jit_helpers.h"
   46.12 +#include "jit_shared.h"
   46.13 +#include "BaseRuntime.h"
   46.14 +#include "jit_function.h"
   46.15  
   46.16  using namespace SourcePawn;
   46.17  
   46.18 @@ -84,12 +86,27 @@
   46.19  	unsigned int index;
   46.20  };
   46.21  
   46.22 +struct call_thunk_t
   46.23 +{
   46.24 +	jitoffs_t patch_addr;
   46.25 +	cell_t pcode_offs;
   46.26 +	jitoffs_t thunk_addr;
   46.27 +};
   46.28 +
   46.29  class CompData : public ICompilation
   46.30  {
   46.31  public:
   46.32 -	CompData() : plugin(NULL), 
   46.33 -		debug(false), profile(0), inline_level(0), rebase(NULL),
   46.34 -		error_set(SP_ERROR_NONE), func_idx(0)
   46.35 +	CompData() 
   46.36 +	:	runtime(NULL),
   46.37 +		plugin(NULL),
   46.38 +		rebase(NULL),
   46.39 +		jit_float_table(NULL),
   46.40 +		profile(0),
   46.41 +		inline_level(0),
   46.42 +		error_set(SP_ERROR_NONE),
   46.43 +		num_thunks(0),
   46.44 +		max_thunks(0),
   46.45 +		thunks(NULL)
   46.46  	{
   46.47  	};
   46.48  	bool SetOption(const char *key, const char *val);
   46.49 @@ -98,18 +115,15 @@
   46.50  public:
   46.51  	BaseRuntime *runtime;			/* runtime handle */
   46.52  	sp_plugin_t *plugin;			/* plugin handle */
   46.53 -	bool debug;						/* whether to compile debug mode */
   46.54 +	uint8_t *rebase;				/* relocation map */
   46.55 +	floattbl_t *jit_float_table;
   46.56 +	cell_t cur_func;				/* current func pcode offset */
   46.57 +	/* Options */
   46.58  	int profile;					/* profiling flags */
   46.59  	int inline_level;				/* inline optimization level */
   46.60 -	jitcode_t rebase;				/* relocation map */
   46.61 +	/* Per-compilation properties */
   46.62  	int error_set;					/* error code to halt process */
   46.63  	unsigned int func_idx;			/* current function index */
   46.64 -	jitoffs_t jit_return;			/* point in main call to return to */
   46.65 -	jitoffs_t jit_verify_addr_eax;
   46.66 -	jitoffs_t jit_verify_addr_edx;
   46.67 -	jitoffs_t jit_break;			/* call to op.break */
   46.68 -	jitoffs_t jit_sysreq_n;			/* call version of op.sysreq.n */
   46.69 -	jitoffs_t jit_genarray;			/* call to genarray intrinsic */
   46.70  	jitoffs_t jit_error_bounds;
   46.71  	jitoffs_t jit_error_divzero;
   46.72  	jitoffs_t jit_error_stacklow;
   46.73 @@ -117,32 +131,47 @@
   46.74  	jitoffs_t jit_error_memaccess;
   46.75  	jitoffs_t jit_error_heaplow;
   46.76  	jitoffs_t jit_error_heapmin;
   46.77 -	jitoffs_t jit_error_array_too_big;
   46.78  	jitoffs_t jit_extern_error;		/* returning generic error */
   46.79  	jitoffs_t jit_sysreq_c;			/* old version! */
   46.80 -	jitoffs_t jit_rounding_table;
   46.81 -	floattbl_t *jit_float_table;
   46.82 -	uint32_t codesize;				/* total codesize */
   46.83 +	uint32_t num_thunks;			/* number of thunks needed */
   46.84 +	uint32_t max_thunks;			/* maximum number of thunks */
   46.85 +	call_thunk_t *thunks;			/* thunk array */
   46.86  };
   46.87  
   46.88  class JITX86
   46.89  {
   46.90  public:
   46.91 +	JITX86();
   46.92 +public:
   46.93 +	bool InitializeJIT();
   46.94 +	void ShutdownJIT();
   46.95  	ICompilation *StartCompilation(BaseRuntime *runtime);
   46.96  	ICompilation *StartCompilation();
   46.97 -	bool Compile(ICompilation *co, BaseRuntime *runtime, int *err);
   46.98 -	void FreePluginVars(sp_plugin_t *pl);
   46.99 +	void SetupContextVars(BaseRuntime *runtime, BaseContext *pCtx, sp_context_t *ctx);
  46.100  	void FreeContextVars(sp_context_t *ctx);
  46.101 -	int ContextExecute(sp_plugin_t *pl, sp_context_t *ctx, uint32_t code_idx, cell_t *result);
  46.102  	SPVM_NATIVE_FUNC CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData);
  46.103  	void DestroyFakeNative(SPVM_NATIVE_FUNC func);
  46.104 +	JitFunction *CompileFunction(BaseRuntime *runtime, cell_t pcode_offs, int *err);
  46.105 +	ICompilation *ApplyOptions(ICompilation *_IN, ICompilation *_OUT);
  46.106 +	int InvokeFunction(BaseRuntime *runtime, JitFunction *fn, cell_t *result);
  46.107 +public:
  46.108 +	void *GetGenArrayIntrinsic();
  46.109 +	void *GetReturnPoint();
  46.110 +	void *GetRoundingTable();
  46.111 +	void *AllocCode(size_t size);
  46.112 +	void FreeCode(void *code);
  46.113 +private:
  46.114 +	void *m_pJitEntry;				/* Entry function */
  46.115 +	void *m_pJitReturn;				/* Return point for errors */
  46.116 +	int m_RoundTable[3];			/* [-1, 0, 1] rounding table */
  46.117 +	void *m_pJitGenArray;			/* Generates an array */
  46.118  };
  46.119  
  46.120  cell_t NativeCallback(sp_context_t *ctx, ucell_t native_idx, cell_t *params);
  46.121 -cell_t NativeCallback_Debug(sp_context_t *ctx, ucell_t native_idx, cell_t *params);
  46.122 -cell_t NativeCallback_Debug_Profile(sp_context_t *ctx, ucell_t native_idx, cell_t *params);
  46.123  cell_t NativeCallback_Profile(sp_context_t *ctx, ucell_t native_idx, cell_t *params);
  46.124 +uint32_t FuncLookup(CompData *data, cell_t pcode_offs);
  46.125  jitoffs_t RelocLookup(JitWriter *jit, cell_t pcode_offs, bool relative=false);
  46.126 +void *CompileThunk(BaseRuntime *runtime, cell_t pcode_ffs, void *jmploc_addr);
  46.127  
  46.128  #define AMX_REG_PRI		REG_EAX
  46.129  #define AMX_REG_ALT		REG_EDX
  46.130 @@ -152,13 +181,20 @@
  46.131  #define AMX_REG_INFO	REG_ESI
  46.132  #define AMX_REG_FRM		REG_EBX
  46.133  
  46.134 +#define AMX_NUM_INFO_VARS	9
  46.135 +
  46.136  #define AMX_INFO_FRM		AMX_REG_INFO	//not relocated
  46.137  #define AMX_INFO_FRAME		0				//(same thing as above) 
  46.138  #define AMX_INFO_HEAP		4				//not relocated
  46.139  #define AMX_INFO_RETVAL		8				//physical
  46.140  #define AMX_INFO_CONTEXT	12				//physical
  46.141  #define AMX_INFO_STACKTOP	16				//relocated
  46.142 +#define AMX_INFO_CIP		20				//pcode CIP
  46.143 +#define AMX_INFO_DATASIZE	24				//plugin->data_size
  46.144 +#define AMX_INFO_MEMORY		28				//plugin->memory
  46.145 +#define AMX_INFO_NSTACK		32				//native stack
  46.146  
  46.147 -extern JITX86 g_Jit1;
  46.148 +extern Knight::KeCodeCache *g_pCodeCache;
  46.149 +extern JITX86 g_Jit;
  46.150  
  46.151  #endif //_INCLUDE_SOURCEPAWN_JIT_X86_H_
    47.1 --- a/sourcepawn/jit/x86/opcode_helpers.cpp	Sun Aug 10 05:39:25 2008 +0000
    47.2 +++ b/sourcepawn/jit/x86/opcode_helpers.cpp	Fri Aug 15 05:22:26 2008 +0000
    47.3 @@ -36,14 +36,11 @@
    47.4  #include "opcode_helpers.h"
    47.5  #include "x86_macros.h"
    47.6  
    47.7 -#define NUM_INFO_PARAMS	5
    47.8 -
    47.9  jitoffs_t Write_Execute_Function(JitWriter *jit)
   47.10  {
   47.11 -	CompData *co = (CompData *)jit->data;
   47.12  	/** 
   47.13  	 * The variables we're passed in:
   47.14 -	 *  sp_context_t *ctx, uint32_t code_idx, cell_t *result
   47.15 +	 *  void *vars[], void *entry_func
   47.16  	 */
   47.17  
   47.18  	/**
   47.19 @@ -65,97 +62,58 @@
   47.20  	IA32_Push_Reg(jit, REG_EDI);
   47.21  	IA32_Push_Reg(jit, REG_EBX);
   47.22  
   47.23 -	//sub esp, 4*n	- reserve info array
   47.24 -	//mov esi, esp	- save info pointer
   47.25 -	IA32_Sub_Rm_Imm8(jit, REG_ESP, 4*NUM_INFO_PARAMS, MOD_REG);
   47.26 -	IA32_Mov_Reg_Rm(jit, AMX_REG_INFO, REG_ESP, MOD_REG);
   47.27 -
   47.28 -	/* Initial memory setup */
   47.29 -	//mov eax, [ebp+16]		- get result pointer
   47.30 -	//mov [esi+8], eax		- store into info pointer
   47.31 -	//mov eax, [ebp+8]		- get context
   47.32 -	//mov [esi+12], eax		- store context into info pointer
   47.33 -	//mov ecx, [eax+<offs>]	- get heap pointer
   47.34 -	//mov [esi+4], ecx		- store heap into info pointer
   47.35 -	//mov ebp, <addr>		- get data pointer
   47.36 -	IA32_Mov_Reg_Rm_Disp8(jit, REG_EAX, REG_EBP, 16);
   47.37 -	IA32_Mov_Rm_Reg_Disp8(jit, AMX_REG_INFO, REG_EAX, AMX_INFO_RETVAL);
   47.38 -	IA32_Mov_Reg_Rm_Disp8(jit, REG_EAX, REG_EBP, 8);
   47.39 -	IA32_Mov_Rm_Reg_Disp8(jit, AMX_REG_INFO, REG_EAX, AMX_INFO_CONTEXT);
   47.40 -	IA32_Mov_Reg_Rm_Disp8(jit, REG_ECX, REG_EAX, offsetof(sp_context_t, hp));
   47.41 -	IA32_Mov_Rm_Reg_Disp8(jit, AMX_REG_INFO, REG_ECX, AMX_INFO_HEAP);
   47.42 -	IA32_Mov_Reg_Imm32(jit, AMX_REG_DAT, jit_int32_t(co->plugin->memory));
   47.43 +	/* Prep us for doing the real work */
   47.44 +	//mov esi, [ebp+param0]			;get vars
   47.45 +	//mov ecx, [ebp+param1]			;get entry addr
   47.46 +	//mov eax, [esi+MEMORY]			;get memory base
   47.47 +	//mov edx, [esi+CONTEXT]		;get context
   47.48 +	IA32_Mov_Reg_Rm_Disp8(jit, REG_ESI, REG_EBP, 8 + 4*0);
   47.49 +	IA32_Mov_Reg_Rm_Disp8(jit, REG_ECX, REG_EBP, 8 + 4*1);
   47.50 +	IA32_Mov_Reg_Rm_Disp8(jit, REG_EAX, REG_ESI, AMX_INFO_MEMORY);
   47.51 +	IA32_Mov_Reg_Rm_Disp8(jit, REG_EDX, REG_ESI, AMX_INFO_CONTEXT);
   47.52  
   47.53 -	/* Frame setup */
   47.54 -	//mov edi, [eax+<offs>]	- get stack pointer
   47.55 -	//add edi, ebp			- relocate to data section
   47.56 -	//mov ebx, edi			- copy sp to frm
   47.57 -	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_STK, REG_EAX, offsetof(sp_context_t, sp));
   47.58 -	IA32_Add_Rm_Reg(jit, AMX_REG_STK, AMX_REG_DAT, MOD_REG);
   47.59 -	IA32_Mov_Reg_Rm(jit, AMX_REG_FRM, AMX_REG_STK, MOD_REG);
   47.60 -
   47.61 -	/* Info memory setup */
   47.62 -	//mov ecx, [eax+<offs>] - copy memsize to temp var
   47.63 -	//add ecx, ebp			- relocate
   47.64 -	//mov [esi+x], ecx		- store relocated
   47.65 -	IA32_Mov_Reg_Imm32(jit, REG_ECX, co->plugin->mem_size);
   47.66 -	IA32_Add_Reg_Rm(jit, AMX_REG_TMP, AMX_REG_DAT, MOD_REG);
   47.67 -	IA32_Mov_Rm_Reg_Disp8(jit, AMX_REG_INFO, REG_ECX, AMX_INFO_STACKTOP);
   47.68 -
   47.69 -	/* Remaining needed vars */
   47.70 -	//mov ecx, [esp+(4*(NUM_INFO_PARAMS+3))+12] - get code index (normally esp+12, but we have another array on the stack)
   47.71 -	//push eax
   47.72 -	//mov eax, <addr of addr of code>
   47.73 -	//mov eax, [eax]
   47.74 -	//add ecx, eax
   47.75 -	//pop eax
   47.76 -	IA32_Mov_Reg_Esp_Disp8(jit, REG_ECX, 12+(4*(NUM_INFO_PARAMS+3)));
   47.77 -	IA32_Push_Reg(jit, REG_EAX);
   47.78 -	IA32_Mov_Reg_Imm32(jit, REG_EAX, jit_int32_t(&co->plugin->codebase));
   47.79 -	IA32_Mov_Reg_Rm(jit, REG_EAX, REG_EAX, MOD_MEM_REG);
   47.80 -	IA32_Add_Reg_Rm(jit, REG_ECX, REG_EAX, MOD_REG);
   47.81 -	IA32_Pop_Reg(jit, REG_EAX);
   47.82 +	/* Set up run-time registers */
   47.83 +	//mov edi, [edx+SP]				;non-reloc SP
   47.84 +	//add edi, eax					;reloc SP
   47.85 +	//mov ebp, eax					;DAT
   47.86 +	//mov ebx, edi					;reloc FRM
   47.87 +	//mov [esi+NSTACK], esp			;save ESP
   47.88 +	IA32_Mov_Reg_Rm_Disp8(jit, REG_EDI, REG_EDX, offsetof(sp_context_t, sp));
   47.89 +	IA32_Add_Rm_Reg(jit, REG_EDI, REG_EAX, MOD_REG);
   47.90 +	IA32_Mov_Reg_Rm(jit, REG_EBP, REG_EAX, MOD_REG);
   47.91 +	IA32_Mov_Reg_Rm(jit, REG_EBX, REG_EDI, MOD_REG);
   47.92 +	IA32_Mov_Rm_Reg_Disp8(jit, REG_ESI, REG_ESP, AMX_INFO_NSTACK);
   47.93  
   47.94  	/* by now, everything is set up, so we can call into the plugin */
   47.95  	//call ecx
   47.96  	IA32_Call_Reg(jit, REG_ECX);
   47.97  
   47.98  	/* if the code flow gets to here, there was a normal return */
   47.99 -	//mov ecx, [esi+8]		- get retval pointer
  47.100 -	//mov [ecx], eax		- store retval from PRI
  47.101 -	//mov eax, SP_ERROR_NONE	- set no error
  47.102 +	//mov ecx, [esi+RETVAL]			;get retval pointer
  47.103 +	//mov [ecx], eax				;store retval from PRI
  47.104 +	//mov eax, SP_ERROR_NONE		;set no error
  47.105  	IA32_Mov_Reg_Rm_Disp8(jit, REG_ECX, AMX_REG_INFO, AMX_INFO_RETVAL);
  47.106  	IA32_Mov_Rm_Reg(jit, REG_ECX, AMX_REG_PRI, MOD_MEM_REG);
  47.107  	IA32_Mov_Reg_Imm32(jit, REG_EAX, SP_ERROR_NONE);
  47.108  
  47.109  	/* save where error checking/halting functions should go to */
  47.110  	jitoffs_t offs_return = jit->get_outputpos();
  47.111 -	//mov esp, esi			- restore stack pointer
  47.112 -	IA32_Mov_Reg_Rm(jit, REG_ESP, REG_ESI, MOD_REG);
  47.113 +	//mov esp, [esi+NSTACK]			;restore stack pointer
  47.114 +	IA32_Mov_Reg_Rm_Disp8(jit, REG_ESP, REG_ESI, AMX_INFO_NSTACK);
  47.115  
  47.116 -	/* _FOR NOW_ ...
  47.117 -	 * We are going to restore SP, HP, and FRM for now.  This is for 
  47.118 -     * debugging only, to check for alignment errors.  As such:
  47.119 -	 * :TODO: probably remove this.
  47.120 -	 */
  47.121 -	//mov ecx, [esi+context]
  47.122 +	/* Restore SP */
  47.123 +	//mov ecx, [esi+CONTEXT]
  47.124  	//sub edi, ebp
  47.125 -	//mov edx, [esi+heap]
  47.126 -	//mov [ecx+sp], edi
  47.127 -	//mov [ecx+hp], edx
  47.128 +	//mov [ecx+SP], edi
  47.129  	IA32_Mov_Reg_Rm_Disp8(jit, REG_ECX, REG_ESI, AMX_INFO_CONTEXT);
  47.130  	IA32_Sub_Reg_Rm(jit, REG_EDI, REG_EBP, MOD_REG);
  47.131 -	IA32_Mov_Reg_Rm_Disp8(jit, REG_EDX, REG_ESI, AMX_INFO_HEAP);
  47.132  	IA32_Mov_Rm_Reg_Disp8(jit, REG_ECX, REG_EDI, offsetof(sp_context_t, sp));
  47.133 -	IA32_Mov_Rm_Reg_Disp8(jit, REG_ECX, REG_EDX, offsetof(sp_context_t, hp));
  47.134  
  47.135 -	//add esp, 4*NUM_INFO_PARAMS
  47.136  	//pop ebx
  47.137  	//pop edi
  47.138  	//pop esi
  47.139  	//pop ebp
  47.140  	//ret
  47.141 -	IA32_Add_Rm_Imm8(jit, REG_ESP, 4*NUM_INFO_PARAMS, MOD_REG);
  47.142  	IA32_Pop_Reg(jit, REG_EBX);
  47.143  	IA32_Pop_Reg(jit, REG_EDI);
  47.144  	IA32_Pop_Reg(jit, REG_ESI);
  47.145 @@ -165,58 +123,22 @@
  47.146  	return offs_return;
  47.147  }
  47.148  
  47.149 -void Write_BreakDebug(JitWriter *jit)
  47.150 -{
  47.151 -	//push edi
  47.152 -	//mov edi, ecx
  47.153 -	//mov ecx, [esi+ctx]
  47.154 -	IA32_Push_Reg(jit, REG_EDI);
  47.155 -	IA32_Mov_Reg_Rm(jit, REG_EDI, REG_ECX, MOD_REG);
  47.156 -	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_TMP, AMX_REG_INFO, AMX_INFO_CONTEXT);
  47.157 -
  47.158 -	//:TODO: align the stack to 16bytes like in sysreq.x
  47.159 -	/* NOTE, Hack! PUSHAD pushes EDI last which still has the CIP */
  47.160 -	//pushad
  47.161 -	//push [esi+frm]
  47.162 -	//push [ctx+basectx]
  47.163 -	//mov ecx, <dbreak>
  47.164 -	//call ecx
  47.165 -	//add esp, 8
  47.166 -	//popad
  47.167 -	IA32_Pushad(jit);
  47.168 -	IA32_Push_Rm_Disp8(jit, AMX_REG_INFO, AMX_INFO_FRAME); //:TODO: move to regs and push? and dont disp for 0
  47.169 -	IA32_Push_Rm_Disp8(jit, AMX_REG_TMP, offsetof(sp_context_t, vm[JITVARS_BASECTX]));
  47.170 -	IA32_Mov_Reg_Imm32(jit, AMX_REG_TMP, jit_int32_t(((CompData *)jit->data)->plugin->dbreak));
  47.171 -	IA32_Call_Reg(jit, AMX_REG_TMP);
  47.172 -	IA32_Add_Rm_Imm8(jit, REG_ESP, 4*2, MOD_REG);
  47.173 -	IA32_Popad(jit);
  47.174 -
  47.175 -	//pop edi
  47.176 -	//ret
  47.177 -	IA32_Pop_Reg(jit, REG_EDI);
  47.178 -	IA32_Return(jit);
  47.179 -}
  47.180 -
  47.181  void Write_GetError(JitWriter *jit)
  47.182  {
  47.183 -	CompData *data = (CompData *)jit->data;
  47.184 -
  47.185  	//mov eax, [esi+info.context]
  47.186  	//mov eax, [eax+ctx.error]
  47.187  	//jmp [jit_return]
  47.188  	IA32_Mov_Reg_Rm_Disp8(jit, REG_EAX, AMX_REG_INFO, AMX_INFO_CONTEXT);
  47.189  	IA32_Mov_Reg_Rm_Disp8(jit, REG_EAX, REG_EAX, offsetof(sp_context_t, n_err));
  47.190 -	IA32_Jump_Imm32_Abs(jit, data->jit_return);
  47.191 +	IA32_Jump_Imm32_Abs(jit, g_Jit.GetReturnPoint());
  47.192  }
  47.193  
  47.194  void Write_SetError(JitWriter *jit, int error)
  47.195  {
  47.196 -	CompData *data = (CompData *)jit->data;
  47.197 -
  47.198  	//mov eax, <error>
  47.199  	//jmp [jit_return]
  47.200  	IA32_Mov_Reg_Imm32(jit, REG_EAX, error);
  47.201 -	IA32_Jump_Imm32_Abs(jit, data->jit_return);
  47.202 +	IA32_Jump_Imm32_Abs(jit, g_Jit.GetReturnPoint());
  47.203  }
  47.204  
  47.205  void Write_Check_DivZero(JitWriter *jit, jit_uint8_t reg)
  47.206 @@ -224,7 +146,7 @@
  47.207  	//test reg, reg
  47.208  	//jz :error
  47.209  	IA32_Test_Rm_Reg(jit, reg, reg, MOD_REG);
  47.210 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_Z, ((CompData *)jit->data)->jit_error_divzero);
  47.211 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_Z, ((CompData *)jit->data)->jit_error_divzero);
  47.212  }
  47.213  
  47.214  void Write_CheckHeap_Min(JitWriter *jit)
  47.215 @@ -238,7 +160,7 @@
  47.216  	//cmp [esi+info.heap], <heaplow>
  47.217  	//jb :error
  47.218  	IA32_Cmp_Rm_Imm32_Disp8(jit, AMX_REG_INFO, AMX_INFO_HEAP, data->plugin->data_size);
  47.219 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_B, data->jit_error_heapmin);
  47.220 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_B, data->jit_error_heapmin);
  47.221  }
  47.222  
  47.223  void Write_CheckHeap_Low(JitWriter *jit)
  47.224 @@ -252,7 +174,7 @@
  47.225  	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_TMP, AMX_REG_INFO, AMX_INFO_HEAP);
  47.226  	IA32_Lea_Reg_DispRegMultImm8(jit, AMX_REG_TMP, AMX_REG_DAT, AMX_REG_TMP, NOSCALE, STACK_MARGIN);
  47.227  	IA32_Cmp_Reg_Rm(jit, AMX_REG_TMP, AMX_REG_STK, MOD_REG);
  47.228 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_A, ((CompData *)jit->data)->jit_error_heaplow);
  47.229 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_A, ((CompData *)jit->data)->jit_error_heaplow);
  47.230  }
  47.231  
  47.232  void Write_CheckStack_Min(JitWriter *jit)
  47.233 @@ -263,7 +185,7 @@
  47.234  	//cmp edi, [esi+info.stacktop]
  47.235  	//jae :error
  47.236  	IA32_Cmp_Reg_Rm_Disp8(jit, AMX_REG_STK, AMX_REG_INFO, AMX_INFO_STACKTOP);
  47.237 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_AE, ((CompData *)jit->data)->jit_error_stackmin);
  47.238 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_AE, ((CompData *)jit->data)->jit_error_stackmin);
  47.239  }
  47.240  
  47.241  void Write_CheckStack_Low(JitWriter *jit)
  47.242 @@ -279,36 +201,15 @@
  47.243  	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_TMP, AMX_REG_INFO, AMX_INFO_HEAP);
  47.244  	IA32_Lea_Reg_DispRegMultImm8(jit, AMX_REG_TMP, AMX_REG_DAT, AMX_REG_TMP, NOSCALE, STACK_MARGIN);
  47.245  	IA32_Cmp_Reg_Rm(jit, AMX_REG_STK, AMX_REG_TMP, MOD_REG);
  47.246 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_B, ((CompData *)jit->data)->jit_error_stacklow);
  47.247 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_B, ((CompData *)jit->data)->jit_error_stacklow);
  47.248  }
  47.249  
  47.250  void Write_Check_VerifyAddr(JitWriter *jit, jit_uint8_t reg)
  47.251  {
  47.252 -	CompData *data = (CompData *)jit->data;
  47.253 -
  47.254  	/* :TODO: Should this be checking for below heaplow?
  47.255  	 * The old JIT did not.
  47.256  	 */
  47.257  
  47.258 -	bool call = false;
  47.259 -	if (!(data->inline_level & JIT_INLINE_ERRORCHECKS))
  47.260 -	{
  47.261 -		/* If we're not in the initial generation phase,
  47.262 -		 * Write a call to the actual routine instead.
  47.263 -		 */
  47.264 -		if ((reg == REG_EAX) && data->jit_verify_addr_eax)
  47.265 -		{
  47.266 -			jitoffs_t call = IA32_Call_Imm32(jit, 0);
  47.267 -			IA32_Write_Jump32(jit, call, data->jit_verify_addr_eax);
  47.268 -			return;
  47.269 -		} else if ((reg == REG_EDX) && data->jit_verify_addr_edx) {
  47.270 -			jitoffs_t call = IA32_Call_Imm32(jit, 0);
  47.271 -			IA32_Write_Jump32(jit, call, data->jit_verify_addr_edx);
  47.272 -			return;
  47.273 -		}
  47.274 -		call = true;
  47.275 -	}
  47.276 -
  47.277  	/** 
  47.278  	 * :TODO: If we can't find a nicer way of doing this,
  47.279  	 *  then scrap it on high optimizations.  The second portion is not needed at all!
  47.280 @@ -318,7 +219,7 @@
  47.281  	//cmp <reg>, <stpu>
  47.282  	//jae :error
  47.283  	IA32_Cmp_Rm_Imm32(jit, MOD_REG, reg, ((CompData *)jit->data)->plugin->mem_size);
  47.284 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_AE, ((CompData *)jit->data)->jit_error_memaccess);
  47.285 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_AE, ((CompData *)jit->data)->jit_error_memaccess);
  47.286  
  47.287  	/* Part 2: Check if we're in the invalid region between HP and SP */
  47.288  	jitoffs_t jmp;
  47.289 @@ -332,13 +233,8 @@
  47.290  	jmp = IA32_Jump_Cond_Imm8(jit, CC_B, 0);
  47.291  	IA32_Lea_Reg_DispRegMultImm8(jit, AMX_REG_TMP, AMX_REG_DAT, reg, NOSCALE, 0);
  47.292  	IA32_Cmp_Reg_Rm(jit, AMX_REG_TMP, AMX_REG_STK, MOD_REG);
  47.293 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_B, ((CompData *)jit->data)->jit_error_memaccess);
  47.294 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_B, ((CompData *)jit->data)->jit_error_memaccess);
  47.295  	IA32_Send_Jump8_Here(jit, jmp);
  47.296 -
  47.297 -	if (call)
  47.298 -	{
  47.299 -		IA32_Return(jit);
  47.300 -	}
  47.301  }
  47.302  
  47.303  void Macro_PushN_Addr(JitWriter *jit, int i)
  47.304 @@ -472,12 +368,7 @@
  47.305  	//call NativeCallback
  47.306  	IA32_Push_Reg(jit, REG_EAX);
  47.307  	jitoffs_t call = IA32_Call_Imm32(jit, 0);
  47.308 -	if (!data->debug)
  47.309 -	{
  47.310 -		IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback);
  47.311 -	} else {
  47.312 -		IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback_Debug);
  47.313 -	}
  47.314 +	IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback);
  47.315  
  47.316  	/* Test for error */
  47.317  	//mov ecx, [esi+context]
  47.318 @@ -485,7 +376,7 @@
  47.319  	//jnz :error
  47.320  	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_TMP, AMX_REG_INFO, AMX_INFO_CONTEXT);
  47.321  	IA32_Cmp_Rm_Disp8_Imm8(jit, AMX_REG_TMP, offsetof(sp_context_t, n_err), 0);
  47.322 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, data->jit_extern_error);
  47.323 +	IA32_Jump_Cond_Imm32_Rel(jit, CC_NZ, data->jit_extern_error);
  47.324  
  47.325  	/* restore what we damaged */
  47.326  	//mov esp, ebx
  47.327 @@ -594,6 +485,8 @@
  47.328   */
  47.329  void WriteIntrinsic_GenArray(JitWriter *jit)
  47.330  {
  47.331 +	jitoffs_t err1, err2;
  47.332 +
  47.333  	/**
  47.334  	 * save important values
  47.335  	 */
  47.336 @@ -635,18 +528,18 @@
  47.337  	/* Test if we have heap space for this */
  47.338  	//mov eax, [esi+info.heap]	;get heap pointer
  47.339  	//lea eax, [eax+edx*4]		;new heap pointer
  47.340 -	//cmp eax, <hlw>			;compare to heap low
  47.341 +	//cmp eax, [esi+info.datasz] ;compare to heap low
  47.342  	//jbe :error				;die if we hit this (it should always be >)
  47.343  	//add eax, ebp				;relocate to stack
  47.344  	//cmp eax, edi				;die if above the stack pointer
  47.345  	//jae :error
  47.346  	IA32_Mov_Reg_Rm_Disp8(jit, REG_EAX, AMX_REG_INFO, AMX_INFO_HEAP);
  47.347  	IA32_Lea_Reg_DispRegMult(jit, REG_EAX, REG_EAX, REG_EDX, SCALE4);
  47.348 -	IA32_Cmp_Rm_Imm32(jit, MOD_REG, REG_EAX, ((CompData *)jit->data)->plugin->data_size);
  47.349 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_BE, ((CompData *)jit->data)->jit_error_array_too_big);
  47.350 +	IA32_Cmp_Reg_Rm_Disp8(jit, REG_EAX, AMX_REG_INFO, AMX_INFO_DATASIZE);
  47.351 +	err1 = IA32_Jump_Cond_Imm32(jit, CC_BE, 0);
  47.352  	IA32_Add_Reg_Rm(jit, REG_EAX, AMX_REG_DAT, MOD_REG);
  47.353  	IA32_Cmp_Reg_Rm(jit, REG_EAX, AMX_REG_STK, MOD_REG);
  47.354 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_AE, ((CompData *)jit->data)->jit_error_array_too_big);
  47.355 +	err2 = IA32_Jump_Cond_Imm32(jit, CC_AE, 0);
  47.356  	
  47.357  	/* Prepare for indirection iteration */
  47.358  	//mov eax, [esi+info.heap]	;get heap pointer
  47.359 @@ -697,107 +590,15 @@
  47.360  	IA32_Pop_Reg(jit, REG_EAX);
  47.361  	IA32_Pop_Reg(jit, REG_EBX);
  47.362  	IA32_Return(jit);
  47.363 -}
  47.364  
  47.365 -void WriteOp_Sysreq_N_Function(JitWriter *jit)
  47.366 -{
  47.367 -	/* The big daddy of opcodes.
  47.368 -	 * eax - num_params
  47.369 -	 * ecx - native index
  47.370 -	 */
  47.371 -	CompData *data = (CompData *)jit->data;
  47.372 -
  47.373 -	/* store the number of parameters on the stack */
  47.374 -	//mov [edi-4], eax
  47.375 -	//sub edi, 4
  47.376 -	IA32_Mov_Rm_Reg_Disp8(jit, AMX_REG_STK, REG_EAX, -4);
  47.377 -	IA32_Sub_Rm_Imm8(jit, AMX_REG_STK, 4, MOD_REG);
  47.378 -
  47.379 -	/* save registers we will need */
  47.380 -	//push eax	; num_params for stack popping
  47.381 -	//push edx
  47.382 -	IA32_Push_Reg(jit, REG_EAX);
  47.383 -	IA32_Push_Reg(jit, AMX_REG_ALT);
  47.384 -
  47.385 -	/* Align the stack to 16 bytes */
  47.386 -	//push ebx
  47.387 -	//mov ebx, esp
  47.388 -	//and esp, 0xFFFFFF0
  47.389 -	//sub esp, 4
  47.390 -	IA32_Push_Reg(jit, REG_EBX);
  47.391 -	IA32_Mov_Reg_Rm(jit, REG_EBX, REG_ESP, MOD_REG);
  47.392 -	IA32_And_Rm_Imm8(jit, REG_ESP, MOD_REG, -16);
  47.393 -	IA32_Sub_Rm_Imm8(jit, REG_ESP, 4, MOD_REG);
  47.394 -
  47.395 -	/* push some callback stuff */
  47.396 -	//push edi		; stack
  47.397 -	//push ecx		; native index
  47.398 -	IA32_Push_Reg(jit, AMX_REG_STK);
  47.399 -	IA32_Push_Reg(jit, REG_ECX);
  47.400 -
  47.401 -	/* Relocate stack, heap, frm information, then store back */
  47.402 -	//mov eax, [esi+context]
  47.403 -	//mov ecx, [esi+hea]
  47.404 -	//sub edi, ebp
  47.405 -	//mov [eax+hp], ecx
  47.406 -	//mov ecx, [esi]
  47.407 -	//mov [eax+sp], edi
  47.408 -	//mov [eax+frm], ecx
  47.409 -	IA32_Mov_Reg_Rm_Disp8(jit, REG_EAX, AMX_REG_INFO, AMX_INFO_CONTEXT);
  47.410 -	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_TMP, AMX_REG_INFO, AMX_INFO_HEAP);
  47.411 -	IA32_Sub_Reg_Rm(jit, AMX_REG_STK, AMX_REG_DAT, MOD_REG);
  47.412 -	IA32_Mov_Rm_Reg_Disp8(jit, REG_EAX, AMX_REG_TMP, offsetof(sp_context_t, hp));
  47.413 -	IA32_Mov_Reg_Rm(jit, AMX_REG_TMP, AMX_INFO_FRM, MOD_MEM_REG);
  47.414 -	IA32_Mov_Rm_Reg_Disp8(jit, REG_EAX, AMX_REG_STK, offsetof(sp_context_t, sp));
  47.415 -	IA32_Mov_Rm_Reg_Disp8(jit, REG_EAX, AMX_REG_TMP, offsetof(sp_context_t, frm));
  47.416 -
  47.417 -	/* finally, push the last parameter and make the call */
  47.418 -	//push eax		; context
  47.419 -	//call NativeCallback
  47.420 -	IA32_Push_Reg(jit, REG_EAX);
  47.421 -	jitoffs_t call = IA32_Call_Imm32(jit, 0);
  47.422 -	if (!data->debug)
  47.423 -	{
  47.424 -		IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback);
  47.425 -	} else {
  47.426 -		IA32_Write_Jump32_Abs(jit, call, (void *)NativeCallback_Debug);
  47.427 -	}
  47.428 -
  47.429 -	/* Test for error */
  47.430 -	//mov ecx, [esi+context]
  47.431 -	//cmp [ecx+err], 0
  47.432 -	//jnz :error
  47.433 -	IA32_Mov_Reg_Rm_Disp8(jit, AMX_REG_TMP, AMX_REG_INFO, AMX_INFO_CONTEXT);
  47.434 -	IA32_Cmp_Rm_Disp8_Imm8(jit, AMX_REG_TMP, offsetof(sp_context_t, n_err), 0);
  47.435 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, data->jit_extern_error);
  47.436 -
  47.437 -	/* restore what we damaged */
  47.438 -	//mov esp, ebx
  47.439 -	//pop ebx
  47.440 -	//add edi, ebp
  47.441 -	//pop edx
  47.442 -	//pop ecx	; num_params
  47.443 -	IA32_Mov_Reg_Rm(jit, REG_ESP, REG_EBX, MOD_REG);
  47.444 -	IA32_Pop_Reg(jit, REG_EBX);
  47.445 -	IA32_Add_Reg_Rm(jit, AMX_REG_STK, AMX_REG_DAT, MOD_REG);
  47.446 -	IA32_Pop_Reg(jit, AMX_REG_ALT);
  47.447 -	IA32_Pop_Reg(jit, REG_ECX);
  47.448 -
  47.449 -	/* pop the AMX stack.  do not check the margins.
  47.450 -	 * Note that this is not a true macro - we don't bother to
  47.451 -	 * set ALT here because nothing will be using it.
  47.452 -	 */
  47.453 -	//lea edi, [edi+ecx*4+4]
  47.454 -	IA32_Lea_Reg_DispRegMultImm8(jit, AMX_REG_STK, AMX_REG_STK, REG_ECX, SCALE4, 4);
  47.455 -
  47.456 -	//ret
  47.457 -	IA32_Return(jit);
  47.458 +	//:error
  47.459 +	IA32_Send_Jump32_Here(jit, err1);
  47.460 +	IA32_Send_Jump32_Here(jit, err2);
  47.461 +	Write_SetError(jit, SP_ERROR_ARRAY_TOO_BIG);
  47.462  }
  47.463  
  47.464  void WriteOp_Tracker_Push_Reg(JitWriter *jit, uint8_t reg)
  47.465  {
  47.466 -	CompData *data = (CompData *)jit->data;
  47.467 -
  47.468  	/* Save registers that may be damaged by the call */
  47.469  	//push eax
  47.470  	//push ecx
  47.471 @@ -824,7 +625,7 @@
  47.472  	//cmp eax, 0
  47.473  	//jnz :error
  47.474  	IA32_Cmp_Rm_Imm8(jit, MOD_REG, REG_EAX, 0);
  47.475 -	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, data->jit_return);
  47.476 +	IA32_Jump_Cond_Imm32_Abs(jit, CC_NZ, g_Jit.GetReturnPoint());
  47.477  
  47.478  	/* Restore */
  47.479  	//pop eax
  47.480 @@ -890,13 +691,6 @@
  47.481  	return SP_ERROR_NONE;
  47.482  }
  47.483  
  47.484 -void Write_RoundingTable(JitWriter *jit)
  47.485 -{
  47.486 -	jit->write_int32(-1);
  47.487 -	jit->write_int32(0);
  47.488 -	jit->write_int32(1);
  47.489 -}
  47.490 -
  47.491  void AlignMe(JitWriter *jit)
  47.492  {
  47.493  	jitoffs_t cur_offs = jit->get_outputpos();
    48.1 --- a/sourcepawn/jit/x86/opcode_helpers.h	Sun Aug 10 05:39:25 2008 +0000
    48.2 +++ b/sourcepawn/jit/x86/opcode_helpers.h	Fri Aug 15 05:22:26 2008 +0000
    48.3 @@ -44,7 +44,6 @@
    48.4  /**
    48.5   * Writes the Sysreq.* opcodes as a function call.
    48.6   */
    48.7 -void WriteOp_Sysreq_N_Function(JitWriter *jit);
    48.8  void WriteOp_Sysreq_C_Function(JitWriter *jit);
    48.9  
   48.10  /**
   48.11 @@ -52,6 +51,8 @@
   48.12   */
   48.13  void WriteIntrinsic_GenArray(JitWriter *jit);
   48.14  
   48.15 +void Write_Check_VerifyAddr(JitWriter *jit, jit_uint8_t reg);
   48.16 +
   48.17  /**
   48.18   * Generates code to set an error state in the VM and return.
   48.19   * This is used for generating the error set points in the VM.
   48.20 @@ -74,12 +75,6 @@
   48.21  void Write_CheckHeap_Low(JitWriter *jit);
   48.22  
   48.23  /**
   48.24 - * Verifies an address by register.  The address must reside
   48.25 - * between DAT and HP and SP and STP.
   48.26 - */
   48.27 -void Write_Check_VerifyAddr(JitWriter *jit, jit_uint8_t reg);
   48.28 -
   48.29 -/**
   48.30   * Checks for division by zero.
   48.31   */
   48.32  void Write_Check_DivZero(JitWriter *jit, jit_uint8_t reg);
   48.33 @@ -303,6 +298,7 @@
   48.34  	OP_GENARRAY_Z,			//-VERIFIED (not tested for 1D arrays)
   48.35  	OP_STRADJUST_PRI,		//VERIFIED
   48.36  	OP_STACKADJUST,			//:TODO: VERIFY
   48.37 +	OP_ENDPROC,				//VERIFIED
   48.38  	OP_FABS,				//VERIFIED
   48.39  	OP_FLOAT,				//VERIFIED
   48.40  	OP_FLOATADD,			//VERIFIED
    49.1 --- a/sourcepawn/jit/x86/opcode_switch.inc	Sun Aug 10 05:39:25 2008 +0000
    49.2 +++ b/sourcepawn/jit/x86/opcode_switch.inc	Fri Aug 15 05:22:26 2008 +0000
    49.3 @@ -676,12 +676,7 @@
    49.4  			}
    49.5  		case OP_SYSREQ_N:
    49.6  			{
    49.7 -				if (data->inline_level & JIT_INLINE_NATIVES)
    49.8 -				{
    49.9 -					WriteOp_Sysreq_N(jit);
   49.10 -				} else {
   49.11 -					WriteOp_Sysreq_N_NoInline(jit);
   49.12 -				}
   49.13 +				WriteOp_Sysreq_N(jit);
   49.14  				break;
   49.15  			}
   49.16  		case OP_TRACKER_PUSH_C:
   49.17 @@ -769,6 +764,11 @@
   49.18  				WriteOp_StackAdjust(jit);
   49.19  				break;
   49.20  			}
   49.21 +		case OP_ENDPROC:
   49.22 +			{
   49.23 +				WriteOp_EndProc(jit);
   49.24 +				break;
   49.25 +			}
   49.26  #if defined USE_UNGEN_OPCODES
   49.27  		#include "ungen_opcode_switch.inc"
   49.28  #endif