core/smn_core.cpp
author Asher Baker <asherkin@gmail.com>
Sat Sep 08 21:02:46 2012 +0100 (2012-09-08)
changeset 3652 e0a6517dcd89
parent 3474 467e6dbfa288
child 3872 4c93f74cae51
permissions -rw-r--r--
Include the auto-version file in the build, so 3rd party plugins compiled aginst the includes get useful versioning info (bug 5453, r=dvander).
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <time.h>
    33 #include <string.h>
    34 #include <stdlib.h>
    35 #include "sm_stringutil.h"
    36 #include "sm_globals.h"
    37 #include "sourcemod.h"
    38 #include "PluginSys.h"
    39 #include "HandleSys.h"
    40 #include "LibrarySys.h"
    41 #include "TimerSys.h"
    42 #include "ForwardSys.h"
    43 #include "Logger.h"
    44 #include "ExtensionSys.h"
    45 #include <sm_trie_tpl.h>
    46 #include <sh_memory.h>
    47 
    48 #if defined PLATFORM_WINDOWS
    49 #include <windows.h>
    50 #elif defined PLATFORM_POSIX
    51 #include <limits.h>
    52 #include <unistd.h>
    53 #include <sys/times.h>
    54 #endif
    55 
    56 HandleType_t g_PlIter;
    57 ConVar sm_datetime_format("sm_datetime_format", "%m/%d/%Y - %H:%M:%S", 0, "Default formatting time rules");
    58 IForward *g_OnLogAction = NULL;
    59 
    60 class CoreNativeHelpers : 
    61 	public SMGlobalClass,
    62 	public IHandleTypeDispatch
    63 {
    64 public:
    65 	void OnSourceModAllInitialized()
    66 	{
    67 		HandleAccess hacc;
    68 		g_HandleSys.InitAccessDefaults(NULL,  &hacc);
    69 		hacc.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
    70 
    71 		g_PlIter = g_HandleSys.CreateType("PluginIterator", this, 0, NULL, NULL, g_pCoreIdent, NULL);
    72 
    73 		g_OnLogAction = g_Forwards.CreateForward("OnLogAction", 
    74 			ET_Hook, 
    75 			5, 
    76 			NULL,
    77 			Param_Cell,
    78 			Param_Cell,
    79 			Param_Cell,
    80 			Param_Cell,
    81 			Param_String);
    82 	}
    83 	void OnHandleDestroy(HandleType_t type, void *object)
    84 	{
    85 		IPluginIterator *iter = (IPluginIterator *)object;
    86 		iter->Release();
    87 	}
    88 	void OnSourceModShutdown()
    89 	{
    90 		g_Forwards.ReleaseForward(g_OnLogAction);
    91 		g_HandleSys.RemoveType(g_PlIter, g_pCoreIdent);
    92 	}
    93 } g_CoreNativeHelpers;
    94 
    95 void LogAction(Handle_t hndl, int type, int client, int target, const char *message)
    96 {
    97 	if (g_OnLogAction->GetFunctionCount())
    98 	{
    99 		cell_t result = 0;
   100 		g_OnLogAction->PushCell(hndl);
   101 		g_OnLogAction->PushCell(type);
   102 		g_OnLogAction->PushCell(client);
   103 		g_OnLogAction->PushCell(target);
   104 		g_OnLogAction->PushString(message);
   105 		g_OnLogAction->Execute(&result);
   106 
   107 		if (result >= (ResultType)Pl_Handled)
   108 		{
   109 			return;
   110 		}
   111 	}
   112 
   113 	const char *logtag = "SM";
   114 	if (type == 2)
   115 	{
   116 		HandleError err;
   117 		IPlugin *pPlugin = g_PluginSys.PluginFromHandle(hndl, &err);
   118 		if (pPlugin)
   119 		{
   120 			logtag = pPlugin->GetFilename();
   121 		}
   122 	}
   123 
   124 	g_Logger.LogMessage("[%s] %s", logtag, message);
   125 }
   126 
   127 static cell_t ThrowError(IPluginContext *pContext, const cell_t *params)
   128 {
   129 	char buffer[512];
   130 
   131 	g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
   132 
   133 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
   134 
   135 	if (pContext->GetLastNativeError() == SP_ERROR_NONE)
   136 	{
   137 		pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
   138 	}
   139 
   140 	return 0;
   141 }
   142 
   143 static cell_t GetTime(IPluginContext *pContext, const cell_t *params)
   144 {
   145 	time_t t = GetAdjustedTime();
   146 	cell_t *addr;
   147 	pContext->LocalToPhysAddr(params[1], &addr);
   148 
   149 	*(time_t *)addr = t;
   150 
   151 	return static_cast<cell_t>(t);
   152 }
   153 
   154 #if defined SUBPLATFORM_SECURECRT
   155 void _ignore_invalid_parameter(
   156 						const wchar_t * expression,
   157 						const wchar_t * function, 
   158 						const wchar_t * file, 
   159 						unsigned int line,
   160 						uintptr_t pReserved
   161 						)
   162 {
   163 	/* Wow we don't care, thanks Microsoft. */
   164 }
   165 #endif
   166 
   167 static cell_t FormatTime(IPluginContext *pContext, const cell_t *params)
   168 {
   169 	char *format, *buffer;
   170 	pContext->LocalToString(params[1], &buffer);
   171 	pContext->LocalToStringNULL(params[3], &format);
   172 
   173 	if (format == NULL)
   174 	{
   175 		format = const_cast<char *>(sm_datetime_format.GetString());
   176 	}
   177 
   178 #if defined SUBPLATFORM_SECURECRT
   179 	_invalid_parameter_handler handler = _set_invalid_parameter_handler(_ignore_invalid_parameter);
   180 #endif
   181 
   182 	time_t t = (params[4] == -1) ? GetAdjustedTime() : (time_t)params[4];
   183 	size_t written = strftime(buffer, params[2], format, localtime(&t));
   184 
   185 #if defined SUBPLATFORM_SECURECRT
   186 	_set_invalid_parameter_handler(handler);
   187 #endif
   188 
   189 	if (params[2] && format[0] != '\0' && !written)
   190 	{
   191 		pContext->ThrowNativeError("Invalid time format or buffer too small");
   192 		return 0;
   193 	}
   194 
   195 	return 1;
   196 }
   197 
   198 static cell_t GetPluginIterator(IPluginContext *pContext, const cell_t *params)
   199 {
   200 	IPluginIterator *iter = g_PluginSys.GetPluginIterator();
   201 
   202 	Handle_t hndl = g_HandleSys.CreateHandle(g_PlIter, iter, pContext->GetIdentity(), g_pCoreIdent, NULL);
   203 
   204 	if (hndl == BAD_HANDLE)
   205 	{
   206 		iter->Release();
   207 	}
   208 
   209 	return hndl;
   210 }
   211 
   212 static cell_t MorePlugins(IPluginContext *pContext, const cell_t *params)
   213 {
   214 	Handle_t hndl = (Handle_t)params[1];
   215 	HandleError err;
   216 	IPluginIterator *pIter;
   217 
   218 	HandleSecurity sec;
   219 	sec.pIdentity = g_pCoreIdent;
   220 	sec.pOwner = pContext->GetIdentity();
   221 
   222 	if ((err=g_HandleSys.ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
   223 	{
   224 		return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   225 	}
   226 
   227 	return pIter->MorePlugins() ? 1 : 0;
   228 }
   229 
   230 static cell_t ReadPlugin(IPluginContext *pContext, const cell_t *params)
   231 {
   232 	Handle_t hndl = (Handle_t)params[1];
   233 	HandleError err;
   234 	IPluginIterator *pIter;
   235 
   236 	HandleSecurity sec;
   237 	sec.pIdentity = g_pCoreIdent;
   238 	sec.pOwner = pContext->GetIdentity();
   239 
   240 	if ((err=g_HandleSys.ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
   241 	{
   242 		return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   243 	}
   244 
   245 	CPlugin *pPlugin = (CPlugin *)pIter->GetPlugin();
   246 	if (!pPlugin)
   247 	{
   248 		return BAD_HANDLE;
   249 	}
   250 
   251 	pIter->NextPlugin();
   252 
   253 	return pPlugin->GetMyHandle();
   254 }
   255 
   256 CPlugin *GetPluginFromHandle(IPluginContext *pContext, Handle_t hndl)
   257 {
   258 	if (hndl == BAD_HANDLE)
   259 	{
   260 		return g_PluginSys.GetPluginByCtx(pContext->GetContext());
   261 	} else {
   262 		HandleError err;
   263 		CPlugin *pPlugin = (CPlugin *)g_PluginSys.PluginFromHandle(hndl, &err);
   264 		if (!pPlugin)
   265 		{
   266 			pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   267 		}
   268 		return pPlugin;
   269 	}
   270 }
   271 
   272 static cell_t GetPluginStatus(IPluginContext *pContext, const cell_t *params)
   273 {
   274 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   275 	if (!pPlugin)
   276 	{
   277 		return 0;
   278 	}
   279 
   280 	return pPlugin->GetStatus();
   281 }
   282 
   283 static cell_t GetPluginFilename(IPluginContext *pContext, const cell_t *params)
   284 {
   285 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   286 	if (!pPlugin)
   287 	{
   288 		return 0;
   289 	}
   290 
   291 	pContext->StringToLocalUTF8(params[2], params[3], pPlugin->GetFilename(), NULL);
   292 
   293 	return 1;
   294 }
   295 
   296 static cell_t IsPluginDebugging(IPluginContext *pContext, const cell_t *params)
   297 {
   298 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   299 	if (!pPlugin)
   300 	{
   301 		return 0;
   302 	}
   303 
   304 	return pPlugin->IsDebugging() ? 1 : 0;
   305 }
   306 
   307 /* Local to plugins only */
   308 enum PluginInfo
   309 {
   310 	PlInfo_Name,			/**< Plugin name */
   311 	PlInfo_Author,			/**< Plugin author */
   312 	PlInfo_Description,		/**< Plugin description */
   313 	PlInfo_Version,			/**< Plugin verison */
   314 	PlInfo_URL,				/**< Plugin URL */
   315 };
   316 
   317 static cell_t GetPluginInfo(IPluginContext *pContext, const cell_t *params)
   318 {
   319 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   320 	if (!pPlugin)
   321 	{
   322 		return 0;
   323 	}
   324 
   325 	const sm_plugininfo_t *info = pPlugin->GetPublicInfo();
   326 
   327 	if (!info)
   328 	{
   329 		return 0;
   330 	}
   331 
   332 	const char *str = NULL;
   333 
   334 	switch ((PluginInfo)params[2])
   335 	{
   336 	case PlInfo_Name:
   337 		{
   338 			str = info->name;
   339 			break;
   340 		}
   341 	case PlInfo_Author:
   342 		{
   343 			str = info->author;
   344 			break;
   345 		}
   346 	case PlInfo_Description:
   347 		{
   348 			str = info->description;
   349 			break;
   350 		}
   351 	case PlInfo_Version:
   352 		{
   353 			str = info->version;
   354 			break;
   355 		}
   356 	case PlInfo_URL:
   357 		{
   358 			str = info->url;
   359 			break;
   360 		}
   361 	}
   362 
   363 	if (!str || str[0] == '\0')
   364 	{
   365 		return 0;
   366 	}
   367 
   368 	pContext->StringToLocalUTF8(params[3], params[4], str, NULL);
   369 
   370 	return 1;
   371 }
   372 
   373 static cell_t SetFailState(IPluginContext *pContext, const cell_t *params)
   374 {
   375 	char *str;
   376 	CPlugin *pPlugin;
   377 
   378 	pContext->LocalToString(params[1], &str);
   379 	pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   380 
   381 	if (params[0] == 1)
   382 	{
   383 		pPlugin->SetErrorState(Plugin_Error, "%s", str);
   384 
   385 		return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", str);
   386 	}
   387 	else
   388 	{
   389 		char buffer[2048];
   390 
   391 		g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
   392 		if (pContext->GetLastNativeError() != SP_ERROR_NONE)
   393 		{
   394 			pPlugin->SetErrorState(Plugin_Error, "%s", str);
   395 			return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "Formatting error (%s)", str);
   396 		}
   397 		else
   398 		{
   399 			pPlugin->SetErrorState(Plugin_Error, "%s", buffer);
   400 			return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
   401 		}
   402 	}
   403 
   404 	return 0;
   405 }
   406 
   407 static cell_t GetSysTickCount(IPluginContext *pContext, const cell_t *params)
   408 {
   409 #if defined PLATFORM_WINDOWS
   410 	return (cell_t)GetTickCount();
   411 #elif defined PLATFORM_POSIX
   412 	tms tm;
   413 	clock_t ticks = times(&tm);
   414 	long ticks_per_sec = sysconf(_SC_CLK_TCK);
   415 	double fticks = (double)ticks / (double)ticks_per_sec;
   416 	fticks *= 1000.0f;
   417 	if (fticks > INT_MAX)
   418 	{
   419 		double r = (int)(fticks / INT_MAX) * (double)INT_MAX;
   420 		fticks -= r;
   421 	}
   422 	return (cell_t)fticks;
   423 #endif
   424 }
   425 
   426 static cell_t AutoExecConfig(IPluginContext *pContext, const cell_t *params)
   427 {
   428 	CPlugin *plugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   429 
   430 	char *cfg, *folder;
   431 	pContext->LocalToString(params[2], &cfg);
   432 	pContext->LocalToString(params[3], &folder);
   433 
   434 	if (cfg[0] == '\0')
   435 	{
   436 		static char temp_str[255];
   437 		static char temp_file[PLATFORM_MAX_PATH];
   438 		char *ptr;
   439 
   440 		g_LibSys.GetFileFromPath(temp_str, sizeof(temp_str), plugin->GetFilename());
   441 		if ((ptr = strstr(temp_str, ".smx")) != NULL)
   442 		{
   443 			*ptr = '\0';
   444 		}
   445 
   446 		/* We have the raw filename! */
   447 		UTIL_Format(temp_file, sizeof(temp_file), "plugin.%s", temp_str);
   448 		cfg = temp_file;
   449 	}
   450 
   451 	plugin->AddConfig(params[1] ? true : false, cfg, folder);
   452 
   453 	return 1;
   454 }
   455 
   456 static cell_t MarkNativeAsOptional(IPluginContext *pContext, const cell_t *params)
   457 {
   458 	char *name;
   459 	uint32_t idx;
   460 	sp_native_t *native;
   461 
   462 	pContext->LocalToString(params[1], &name);
   463 	if (pContext->FindNativeByName(name, &idx) != SP_ERROR_NONE)
   464 	{
   465 		/* Oops! This HAS to silently fail! */
   466 		return 0;
   467 	}
   468 
   469 	pContext->GetNativeByIndex(idx, &native);
   470 
   471 	native->flags |= SP_NTVFLAG_OPTIONAL;
   472 
   473 	return 1;
   474 }
   475 
   476 static cell_t RegPluginLibrary(IPluginContext *pContext, const cell_t *params)
   477 {
   478 	char *name;
   479 	CPlugin *pl = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   480 
   481 	pContext->LocalToString(params[1], &name);
   482 
   483 	pl->AddLibrary(name);
   484 
   485 	return 1;
   486 }
   487 
   488 static cell_t LibraryExists(IPluginContext *pContext, const cell_t *params)
   489 {
   490 	char *str;
   491 	pContext->LocalToString(params[1], &str);
   492 
   493 	if (strcmp(str, "__CanTestFeatures__") == 0)
   494 	{
   495 		return 1;
   496 	}
   497 
   498 	if (g_PluginSys.LibraryExists(str))
   499 	{
   500 		return 1;
   501 	}
   502 
   503 	if (g_Extensions.LibraryExists(str))
   504 	{
   505 		return 1;
   506 	}
   507 
   508 	return 0;
   509 }
   510 
   511 static cell_t sm_LogAction(IPluginContext *pContext, const cell_t *params)
   512 {
   513 	char buffer[2048];
   514 	g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
   515 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
   516 
   517 	if (pContext->GetLastNativeError() != SP_ERROR_NONE)
   518 	{
   519 		return 0;
   520 	}
   521 
   522 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   523 
   524 	LogAction(pPlugin->GetMyHandle(), 2, params[1], params[2], buffer);
   525 
   526 	return 1;
   527 }
   528 
   529 static cell_t LogToFile(IPluginContext *pContext, const cell_t *params)
   530 {
   531 	char *file;
   532 	pContext->LocalToString(params[1], &file);
   533 
   534 	char path[PLATFORM_MAX_PATH];
   535 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
   536 
   537 	FILE *fp = fopen(path, "at");
   538 	if (!fp)
   539 	{
   540 		return pContext->ThrowNativeError("Could not open file \"%s\"", path);
   541 	}
   542 
   543 	char buffer[2048];
   544 	g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
   545 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
   546 
   547 	if (pContext->GetLastNativeError() != SP_ERROR_NONE)
   548 	{
   549 		fclose(fp);
   550 		return 0;
   551 	}
   552 
   553 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   554 
   555 	g_Logger.LogToOpenFile(fp, "[%s] %s", pPlugin->GetFilename(), buffer);
   556 
   557 	fclose(fp);
   558 
   559 	return 1;
   560 }
   561 
   562 static cell_t LogToFileEx(IPluginContext *pContext, const cell_t *params)
   563 {
   564 	char *file;
   565 	pContext->LocalToString(params[1], &file);
   566 
   567 	char path[PLATFORM_MAX_PATH];
   568 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
   569 
   570 	FILE *fp = fopen(path, "at");
   571 	if (!fp)
   572 	{
   573 		return pContext->ThrowNativeError("Could not open file \"%s\"", path);
   574 	}
   575 
   576 	char buffer[2048];
   577 	g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
   578 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
   579 
   580 	if (pContext->GetLastNativeError() != SP_ERROR_NONE)
   581 	{
   582 		fclose(fp);
   583 		return 0;
   584 	}
   585 
   586 	g_Logger.LogToOpenFile(fp, "%s", buffer);
   587 
   588 	fclose(fp);
   589 
   590 	return 1;
   591 }
   592 
   593 static cell_t GetExtensionFileStatus(IPluginContext *pContext, const cell_t *params)
   594 {
   595 	char *str;
   596 	pContext->LocalToString(params[1], &str);
   597 
   598 	IExtension *pExtension = g_Extensions.FindExtensionByFile(str);
   599 	
   600 	if (!pExtension)
   601 	{
   602 		return -2;
   603 	}
   604 	
   605 	if (!pExtension->IsLoaded())
   606 	{
   607 		return -1;
   608 	}
   609 
   610 	char *error;
   611 	pContext->LocalToString(params[2], &error);
   612 	if (!pExtension->IsRunning(error, params[3]))
   613 	{
   614 		return 0;
   615 	}
   616 
   617 	return 1;
   618 }
   619 
   620 static cell_t FindPluginByNumber(IPluginContext *pContext, const cell_t *params)
   621 {
   622 	CPlugin *pPlugin = g_PluginSys.GetPluginByOrder(params[1]);
   623 	
   624 	if (pPlugin == NULL)
   625 	{
   626 		return BAD_HANDLE;
   627 	}
   628 
   629 	return pPlugin->GetMyHandle();
   630 }
   631 
   632 static cell_t VerifyCoreVersion(IPluginContext *pContext, const cell_t *params)
   633 {
   634 	return 4;
   635 }
   636 
   637 static cell_t GetFeatureStatus(IPluginContext *pContext, const cell_t *params)
   638 {
   639 	FeatureType type = (FeatureType)params[1];
   640 	char *name;
   641 
   642 	pContext->LocalToString(params[2], &name);
   643 
   644 	return g_ShareSys.TestFeature(pContext->GetRuntime(),type, name);
   645 }
   646 
   647 static cell_t RequireFeature(IPluginContext *pContext, const cell_t *params)
   648 {
   649 	FeatureType type = (FeatureType)params[1];
   650 	char *name;
   651 
   652 	pContext->LocalToString(params[2], &name);
   653 
   654 	if (g_ShareSys.TestFeature(pContext->GetRuntime(),type, name) != FeatureStatus_Available)
   655 	{
   656 		char buffer[255];
   657 		char *msg = buffer;
   658 		char default_message[255];
   659 		CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   660 
   661 		g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
   662 		if (pContext->GetLastNativeError() != SP_ERROR_NONE || buffer[0] == '\0')
   663 		{
   664 			UTIL_Format(default_message, sizeof(default_message), "Feature \"%s\" not available", name);
   665 			msg = default_message;
   666 		}
   667 		pPlugin->SetErrorState(Plugin_Error, "%s", msg);
   668 		return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", msg);
   669 	}
   670 
   671 	return 1;
   672 }
   673 
   674 enum NumberType
   675 {
   676 	NumberType_Int8,
   677 	NumberType_Int16,
   678 	NumberType_Int32
   679 };
   680 
   681 //memory addresses below 0x10000 are automatically considered invalid for dereferencing
   682 #define VALID_MINIMUM_MEMORY_ADDRESS 0x10000
   683 
   684 static cell_t LoadFromAddress(IPluginContext *pContext, const cell_t *params)
   685 {
   686 	void *addr = reinterpret_cast<void*>(params[1]);
   687 
   688 	if (addr == NULL)
   689 	{
   690 		pContext->ThrowNativeError("Address cannot be null");
   691 	}
   692 	else if (reinterpret_cast<uintptr_t>(addr) < VALID_MINIMUM_MEMORY_ADDRESS)
   693 	{
   694 		pContext->ThrowNativeError("Invalid address 0x%x is pointing to reserved memory.", addr);
   695 	}
   696 	NumberType size = static_cast<NumberType>(params[2]);
   697 
   698 	switch(size)
   699 	{
   700 	case NumberType_Int8:
   701 		return *reinterpret_cast<uint8_t*>(addr);
   702 	case NumberType_Int16:
   703 		return *reinterpret_cast<uint16_t*>(addr);
   704 	case NumberType_Int32:
   705 		return *reinterpret_cast<uint32_t*>(addr);
   706 	default:
   707 		pContext->ThrowNativeError("Invalid number types %d", size);
   708 	}
   709 
   710 	return 1;
   711 }
   712 
   713 
   714 static cell_t StoreToAddress(IPluginContext *pContext, const cell_t *params)
   715 {
   716 	void *addr = reinterpret_cast<void*>(params[1]);
   717 
   718 	if (addr == NULL)
   719 	{
   720 		pContext->ThrowNativeError("Address cannot be null");
   721 	}
   722 	else if (reinterpret_cast<uintptr_t>(addr) < VALID_MINIMUM_MEMORY_ADDRESS)
   723 	{
   724 		pContext->ThrowNativeError("Invalid address 0x%x is pointing to reserved memory.", addr);
   725 	}
   726 	cell_t data = params[2];
   727 
   728 	NumberType size = static_cast<NumberType>(params[3]);
   729 
   730 	switch(size)
   731 	{
   732 	case NumberType_Int8:
   733 		SourceHook::SetMemAccess(addr, sizeof(uint8_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   734 		*reinterpret_cast<uint8_t*>(addr) = data;
   735 		break;
   736 	case NumberType_Int16:
   737 		SourceHook::SetMemAccess(addr, sizeof(uint16_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   738 		*reinterpret_cast<uint16_t*>(addr) = data;
   739 		break;
   740 	case NumberType_Int32:
   741 		SourceHook::SetMemAccess(addr, sizeof(uint32_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   742 		*reinterpret_cast<uint32_t*>(addr) = data;
   743 		break;
   744 	default:
   745 		pContext->ThrowNativeError("Invalid number types %d", size);
   746 	}
   747 
   748 	return 1;
   749 }
   750 
   751 REGISTER_NATIVES(coreNatives)
   752 {
   753 	{"AutoExecConfig",			AutoExecConfig},
   754 	{"GetPluginFilename",		GetPluginFilename},
   755 	{"GetPluginInfo",			GetPluginInfo},
   756 	{"GetPluginIterator",		GetPluginIterator},
   757 	{"GetPluginStatus",			GetPluginStatus},
   758 	{"GetSysTickCount",			GetSysTickCount},
   759 	{"GetTime",					GetTime},
   760 	{"IsPluginDebugging",		IsPluginDebugging},
   761 	{"MorePlugins",				MorePlugins},
   762 	{"ReadPlugin",				ReadPlugin},
   763 	{"ThrowError",				ThrowError},
   764 	{"SetFailState",			SetFailState},
   765 	{"FormatTime",				FormatTime},
   766 	{"MarkNativeAsOptional",	MarkNativeAsOptional},
   767 	{"RegPluginLibrary",		RegPluginLibrary},
   768 	{"LibraryExists",			LibraryExists},
   769 	{"LogAction",				sm_LogAction},
   770 	{"LogToFile",				LogToFile},
   771 	{"LogToFileEx",				LogToFileEx},
   772 	{"GetExtensionFileStatus",	GetExtensionFileStatus},
   773 	{"FindPluginByNumber",		FindPluginByNumber},
   774 	{"VerifyCoreVersion",		VerifyCoreVersion},
   775 	{"GetFeatureStatus",        GetFeatureStatus},
   776 	{"RequireFeature",          RequireFeature},
   777 	{"LoadFromAddress",         LoadFromAddress},
   778 	{"StoreToAddress",          StoreToAddress},
   779 	{NULL,						NULL},
   780 };
   781