core/systems/ForwardSys.cpp
author David Anderson <dvander@alliedmods.net>
Mon Oct 22 16:48:54 2007 +0000 (2007-10-22)
changeset 1639 5c7fffd146ae
parent 1339 02e8f2c0f8af
child 1947 e73a1e51833b
permissions -rw-r--r--
fixed linux build
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2007 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 <assert.h>
    33 #include <stdarg.h>
    34 #include <string.h>
    35 #include "ForwardSys.h"
    36 #include "PluginSys.h"
    37 #include "ShareSys.h"
    38 #include "DebugReporter.h"
    39 
    40 CForwardManager g_Forwards;
    41 
    42 /**
    43  * Genesis turns to its source, reduction occurs stepwise although the essence is all one.
    44  * End of line.  FTL system check.
    45  *
    46  * :TODO: WHAT NEEDS TO BE TESTED IN THIS BEAST
    47  * VARARG FUNCTIONS:
    48  * - Pushing no varargs
    49  */
    50 
    51 // :TODO: IMPORTANT!!! The result pointer arg in the execute function maybe invalid if the forward fails
    52 // so later evaluation of this result may cause problems on higher levels of abstraction. DOCUMENT OR FIX ALL FORWARDS!
    53 
    54 CForwardManager::~CForwardManager()
    55 {
    56 	CStack<CForward *>::iterator iter;
    57 	for (iter=m_FreeForwards.begin(); iter!=m_FreeForwards.end(); iter++)
    58 	{
    59 		delete (*iter);
    60 	}
    61 	m_FreeForwards.popall();
    62 }
    63 
    64 void CForwardManager::OnSourceModAllInitialized()
    65 {
    66 	g_PluginSys.AddPluginsListener(this);
    67 	g_ShareSys.AddInterface(NULL, this);
    68 }
    69 
    70 IForward *CForwardManager::CreateForward(const char *name, ExecType et, unsigned int num_params, const ParamType *types, ...)
    71 {
    72 	CForward *fwd;
    73 	va_list ap;
    74 	va_start(ap, types);
    75 	
    76 	fwd = CForward::CreateForward(name, et, num_params, types, ap);
    77 
    78 	va_end(ap);
    79 
    80 	if (fwd)
    81 	{
    82 		g_PluginSys.AddFunctionsToForward(name, fwd);
    83 
    84 		m_managed.push_back(fwd);
    85 	}
    86 
    87 	return fwd;
    88 }
    89 
    90 IChangeableForward *CForwardManager::CreateForwardEx(const char *name, ExecType et, int num_params, const ParamType *types, ...)
    91 {
    92 	CForward *fwd;
    93 	va_list ap;
    94 	va_start(ap, types);
    95 
    96 	fwd = CForward::CreateForward(name, et, num_params, types, ap);
    97 
    98 	va_end(ap);
    99 
   100 	if (fwd)
   101 	{
   102 		m_unmanaged.push_back(fwd);
   103 	}
   104 
   105 	return fwd;
   106 }
   107 
   108 void CForwardManager::OnPluginLoaded(IPlugin *plugin)
   109 {
   110 	/* Attach any globally managed forwards */
   111 	List<CForward *>::iterator iter;
   112 	CForward *fwd;
   113 
   114 	for (iter=m_managed.begin(); iter!=m_managed.end(); iter++)
   115 	{
   116 		fwd = (*iter);
   117 		IPluginFunction *pFunc = plugin->GetBaseContext()->GetFunctionByName(fwd->GetForwardName());
   118 		if (pFunc)
   119 		{
   120 			fwd->AddFunction(pFunc);
   121 		}
   122 	}
   123 }
   124 
   125 void CForwardManager::OnPluginUnloaded(IPlugin *plugin)
   126 {
   127 	List<CForward *>::iterator iter;
   128 	CForward *fwd;
   129 
   130 	for (iter=m_managed.begin(); iter!=m_managed.end(); iter++)
   131 	{
   132 		fwd = (*iter);
   133 		fwd->RemoveFunctionsOfPlugin(plugin);
   134 	}
   135 
   136 	for (iter=m_unmanaged.begin(); iter!=m_unmanaged.end(); iter++)
   137 	{
   138 		fwd = (*iter);
   139 		fwd->RemoveFunctionsOfPlugin(plugin);
   140 	}
   141 }
   142 
   143 IForward *CForwardManager::FindForward(const char *name, IChangeableForward **ifchng)
   144 {
   145 	List<CForward *>::iterator iter;
   146 	CForward *fwd;
   147 
   148 	for (iter=m_managed.begin(); iter!=m_managed.end(); iter++)
   149 	{
   150 		fwd = (*iter);
   151 		if (strcmp(fwd->GetForwardName(), name) == 0)
   152 		{
   153 			if (ifchng)
   154 			{
   155 				*ifchng = NULL;
   156 			}
   157 			return fwd;
   158 		}
   159 	}
   160 
   161 	for (iter=m_unmanaged.begin(); iter!=m_unmanaged.end(); iter++)
   162 	{
   163 		fwd = (*iter);
   164 		if (strcmp(fwd->GetForwardName(), name) == 0)
   165 		{
   166 			if (ifchng)
   167 			{
   168 				*ifchng = fwd;
   169 			}
   170 			return fwd;
   171 		}
   172 	}
   173 
   174 	if (ifchng)
   175 	{
   176 		*ifchng = NULL;
   177 	}
   178 
   179 	return NULL;
   180 }
   181 
   182 void CForwardManager::ReleaseForward(IForward *forward)
   183 {
   184 	ForwardFree(static_cast<CForward *>(forward));
   185 }
   186 
   187 void CForwardManager::ForwardFree(CForward *fwd)
   188 {
   189 	m_FreeForwards.push(fwd);
   190 	m_managed.remove(fwd);
   191 }
   192 
   193 CForward *CForwardManager::ForwardMake()
   194 {
   195 	CForward *fwd;
   196 	if (m_FreeForwards.empty())
   197 	{
   198 		fwd = new CForward;
   199 	} else {
   200 		fwd = m_FreeForwards.front();
   201 		m_FreeForwards.pop();
   202 	}
   203 	return fwd;
   204 }
   205 
   206 void CForwardManager::OnPluginPauseChange(IPlugin *plugin, bool paused)
   207 {
   208 	/* No longer used */
   209 }
   210 
   211 /*************************************
   212  * ACTUAL FORWARD API IMPLEMENTATION *
   213  *************************************/
   214 
   215 CForward *CForward::CreateForward(const char *name, ExecType et, unsigned int num_params, const ParamType *types, va_list ap)
   216 {
   217 	ParamType _types[SP_MAX_EXEC_PARAMS];
   218 
   219 	if (num_params > SP_MAX_EXEC_PARAMS)
   220 	{
   221 		return NULL;
   222 	}
   223 	
   224 	if (types == NULL && num_params)
   225 	{
   226 		for (unsigned int i=0; i<num_params; i++)
   227 		{
   228 			_types[i] = (ParamType)va_arg(ap, int);
   229 			if (_types[i] == Param_VarArgs && (i != num_params - 1))
   230 			{
   231 				return NULL;
   232 			}
   233 		}
   234 		types = _types;
   235 	} else {
   236 		for (unsigned int i=0; i<num_params; i++)
   237 		{
   238 			_types[i] = types[i];
   239 			if (types[i] == Param_VarArgs && (i != num_params - 1))
   240 			{
   241 				return NULL;
   242 			}
   243 		}
   244 	}
   245 
   246 	/* First parameter can never be varargs */
   247 	if (num_params && _types[0] == Param_VarArgs)
   248 	{
   249 		return NULL;
   250 	}
   251 
   252 	CForward *pForward = g_Forwards.ForwardMake();
   253 	pForward->m_curparam = 0;
   254 	pForward->m_ExecType = et;
   255 	snprintf(pForward->m_name, FORWARDS_NAME_MAX, "%s", name ? name : "");
   256 	
   257 	for (unsigned int i=0; i<num_params; i++)
   258 	{
   259 		pForward->m_types[i] = _types[i];
   260 	}
   261 
   262 	if (num_params && _types[num_params-1] == Param_VarArgs)
   263 	{
   264 		pForward->m_varargs = num_params--;
   265 	} else {
   266 		pForward->m_varargs = false;
   267 	}
   268 
   269 	pForward->m_numparams = num_params;
   270 	pForward->m_errstate = SP_ERROR_NONE;
   271 
   272 	pForward->m_functions.clear();
   273 
   274 	return pForward;
   275 }
   276 
   277 int CForward::Execute(cell_t *result, IForwardFilter *filter)
   278 {
   279 	if (m_errstate)
   280 	{
   281 		int err = m_errstate;
   282 		Cancel();
   283 		return err;
   284 	}
   285 
   286 	if (filter)
   287 	{
   288 		filter->OnExecuteBegin();
   289 	}
   290 
   291 	FuncIter iter = m_functions.begin();
   292 	IPluginFunction *func;
   293 	cell_t cur_result = 0;
   294 	cell_t high_result = 0;
   295 	int err;
   296 	unsigned int failed=0, success=0;
   297 	unsigned int num_params = m_curparam;
   298 	FwdParamInfo temp_info[SP_MAX_EXEC_PARAMS];
   299 	FwdParamInfo *param;
   300 	ParamType type;
   301 
   302 	/* Save local, reset */
   303 	memcpy(temp_info, m_params, sizeof(m_params));
   304 	m_curparam = 0;
   305 
   306 	for (iter=m_functions.begin(); iter!=m_functions.end(); iter++)
   307 	{
   308 		func = (*iter);
   309 
   310 		for (unsigned int i=0; i<num_params; i++)
   311 		{
   312 			int err = SP_ERROR_PARAM;
   313 			param = &temp_info[i];
   314 			if (i >= m_numparams || m_types[i] == Param_Any)
   315 			{
   316 				type = param->pushedas;
   317 			} else {
   318 				type = m_types[i];
   319 			}
   320 			if ((i >= m_numparams) || (type & SP_PARAMFLAG_BYREF))
   321 			{
   322 				/* If we're byref or we're vararg, we always push everything by ref.
   323 				 * Even if they're byval, we must push them byref.
   324 				 */
   325 				if (type == Param_String)
   326 				{
   327 					err = func->PushStringEx((char *)param->byref.orig_addr, param->byref.cells, param->byref.sz_flags, param->byref.flags);
   328 				} else if (type == Param_Float || type == Param_Cell) {
   329 					err = func->PushCellByRef(&param->val); 
   330 				} else {
   331 					err = func->PushArray(param->byref.orig_addr, param->byref.cells, param->byref.flags);
   332 					assert(type == Param_Array || type == Param_FloatByRef || type == Param_CellByRef);
   333 				}
   334 			} else {
   335 				/* If we're not byref or not vararg, our job is a bit easier. */
   336 				assert(type == Param_Cell || type == Param_Float);
   337 				err = func->PushCell(param->val);
   338 			}
   339 			if (err != SP_ERROR_NONE)
   340 			{
   341 				if (!filter || !filter->OnErrorReport(this, func, err))
   342 				{
   343 					g_DbgReporter.GenerateError(func->GetParentContext(), 
   344 						func->GetFunctionID(), 
   345 						err, 
   346 						"Failed to push parameter while executing forward");
   347 				}
   348 				continue;
   349 			}
   350 		}
   351 		
   352 		/* Call the function and deal with the return value. */
   353 		if ((err=func->Execute(&cur_result)) != SP_ERROR_NONE)
   354 		{
   355 			if (filter)
   356 			{
   357 				filter->OnErrorReport(this, func, err);
   358 			}
   359 			failed++;
   360 		} else {
   361 			success++;
   362 			switch (m_ExecType)
   363 			{
   364 			case ET_Event:
   365 				{
   366 					if (cur_result > high_result)
   367 					{
   368 						high_result = cur_result;
   369 					}
   370 					break;
   371 				}
   372 			case ET_Hook:
   373 				{
   374 					if (cur_result > high_result)
   375 					{
   376 						high_result = cur_result;
   377 						if ((ResultType)high_result == Pl_Stop)
   378 						{
   379 							goto done;
   380 						}
   381 					}
   382 					break;
   383 				}
   384 			case ET_Custom:
   385 				{
   386 					if (filter)
   387 					{
   388 						if (filter->OnFunctionReturn(this, func, &cur_result) == Pl_Stop)
   389 						{
   390 							goto done;
   391 						}
   392 					}
   393 					break;
   394 				}
   395 			default:
   396 				{
   397 					break;
   398 				}
   399 			}
   400 		}
   401 	}
   402 
   403 done:
   404 	if (success)
   405 	{
   406 		if (m_ExecType == ET_Event || m_ExecType == ET_Hook)
   407 		{
   408 			cur_result = high_result;
   409 		} else if (m_ExecType == ET_Ignore) {
   410 			cur_result = 0;
   411 		}
   412 		if (result)
   413 		{
   414 			*result = cur_result;
   415 		}
   416 	}
   417 
   418 	if (filter)
   419 	{
   420 		filter->OnExecuteEnd(&cur_result, success, failed);
   421 	}
   422 
   423 	return SP_ERROR_NONE;
   424 }
   425 
   426 int CForward::PushCell(cell_t cell)
   427 {
   428 	if (m_curparam < m_numparams)
   429 	{
   430 		if (m_types[m_curparam] == Param_Any)
   431 		{
   432 			m_params[m_curparam].pushedas = Param_Cell;
   433 		} else if (m_types[m_curparam] != Param_Cell) {
   434 			return SetError(SP_ERROR_PARAM);
   435 		}
   436 	} else {
   437 		if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
   438 		{
   439 			return SetError(SP_ERROR_PARAMS_MAX);
   440 		}
   441 		m_params[m_curparam].pushedas = Param_Cell;
   442 	}
   443 
   444 	m_params[m_curparam++].val = cell;
   445 
   446 	return SP_ERROR_NONE;
   447 }
   448 
   449 int CForward::PushFloat(float number)
   450 {
   451 	if (m_curparam < m_numparams)
   452 	{
   453 		if (m_types[m_curparam] == Param_Any)
   454 		{
   455 			m_params[m_curparam].pushedas = Param_Float;
   456 		} else if (m_types[m_curparam] != Param_Float) {
   457 			return SetError(SP_ERROR_PARAM);
   458 		}
   459 	} else {
   460 		if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
   461 		{
   462 			return SetError(SP_ERROR_PARAMS_MAX);
   463 		}
   464 		m_params[m_curparam].pushedas = Param_Float;
   465 	}
   466 
   467 	m_params[m_curparam++].val = *(cell_t *)&number;
   468 
   469 	return SP_ERROR_NONE;
   470 }
   471 
   472 int CForward::PushCellByRef(cell_t *cell, int flags)
   473 {
   474 	if (m_curparam < m_numparams)
   475 	{
   476 		if (m_types[m_curparam] == Param_Any)
   477 		{
   478 			m_params[m_curparam].pushedas = Param_CellByRef;
   479 		} else if (m_types[m_curparam] != Param_CellByRef) {
   480 			return SetError(SP_ERROR_PARAM);
   481 		}
   482 	} else {
   483 		if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
   484 		{
   485 			return SetError(SP_ERROR_PARAMS_MAX);
   486 		}
   487 		m_params[m_curparam].pushedas = Param_CellByRef;
   488 	}
   489 
   490 	_Int_PushArray(cell, 1, flags);
   491 	m_curparam++;
   492 
   493 	return SP_ERROR_NONE;
   494 }
   495 
   496 int CForward::PushFloatByRef(float *num, int flags)
   497 {
   498 	if (m_curparam < m_numparams)
   499 	{
   500 		if (m_types[m_curparam] == Param_Any)
   501 		{
   502 			m_params[m_curparam].pushedas = Param_FloatByRef;
   503 		} else if (m_types[m_curparam] != Param_FloatByRef) {
   504 			return SetError(SP_ERROR_PARAM);
   505 		}
   506 	} else {
   507 		if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
   508 		{
   509 			return SetError(SP_ERROR_PARAMS_MAX);
   510 		}
   511 		m_params[m_curparam].pushedas = Param_FloatByRef;
   512 	}
   513 
   514 	_Int_PushArray((cell_t *)num, 1, flags);
   515 	m_curparam++;
   516 
   517 	return SP_ERROR_NONE;
   518 }
   519 
   520 void CForward::_Int_PushArray(cell_t *inarray, unsigned int cells, int flags)
   521 {
   522 	m_params[m_curparam].byref.cells = cells;
   523 	m_params[m_curparam].byref.flags = flags;
   524 	m_params[m_curparam].byref.orig_addr = inarray;
   525 }
   526 
   527 int CForward::PushArray(cell_t *inarray, unsigned int cells, int flags)
   528 {
   529 	/* We don't allow this here */
   530 	if (!inarray)
   531 	{
   532 		return SetError(SP_ERROR_PARAM);
   533 	}
   534 
   535 	if (m_curparam < m_numparams)
   536 	{
   537 		if (m_types[m_curparam] == Param_Any)
   538 		{
   539 			m_params[m_curparam].pushedas = Param_Array;
   540 		} else if (m_types[m_curparam] != Param_Array) {
   541 			return SetError(SP_ERROR_PARAM);
   542 		}
   543 	} else {
   544 		if (!m_varargs || m_curparam > SP_MAX_EXEC_PARAMS)
   545 		{
   546 			return SetError(SP_ERROR_PARAMS_MAX);
   547 		}
   548 		m_params[m_curparam].pushedas = Param_Array;
   549 	}
   550 
   551 	_Int_PushArray(inarray, cells, flags);
   552 
   553 	m_curparam++;
   554 
   555 	return SP_ERROR_NONE;
   556 }
   557 
   558 void CForward::_Int_PushString(cell_t *inarray, unsigned int cells, int sz_flags, int cp_flags)
   559 {
   560 	m_params[m_curparam].byref.cells = cells;	/* Notice this contains the char count not cell count */
   561 	m_params[m_curparam].byref.flags = cp_flags;
   562 	m_params[m_curparam].byref.orig_addr = inarray;
   563 	m_params[m_curparam].byref.sz_flags = sz_flags;
   564 }
   565 
   566 int CForward::PushString(const char *string)
   567 {
   568 	if (m_curparam < m_numparams)
   569 	{
   570 		if (m_types[m_curparam] == Param_Any)
   571 		{
   572 			m_params[m_curparam].pushedas = Param_String;
   573 		} else if (m_types[m_curparam] != Param_String) {
   574 			return SetError(SP_ERROR_PARAM);
   575 		}
   576 	} else {
   577 		if (!m_varargs || m_curparam > SP_MAX_EXEC_PARAMS)
   578 		{
   579 			return SetError(SP_ERROR_PARAMS_MAX);
   580 		}
   581 		m_params[m_curparam].pushedas = Param_String;
   582 	}
   583 
   584 	_Int_PushString((cell_t *)string, strlen(string)+1, SM_PARAM_STRING_COPY, 0);
   585 	m_curparam++;
   586 
   587 	return SP_ERROR_NONE;
   588 }
   589 
   590 int CForward::PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags)
   591 {
   592 	if (m_curparam < m_numparams)
   593 	{
   594 		if (m_types[m_curparam] == Param_Any)
   595 		{
   596 			m_params[m_curparam].pushedas = Param_String;
   597 		} else if (m_types[m_curparam] != Param_String) {
   598 			return SetError(SP_ERROR_PARAM);
   599 		}
   600 	} else {
   601 		if (!m_varargs || m_curparam > SP_MAX_EXEC_PARAMS)
   602 		{
   603 			return SetError(SP_ERROR_PARAMS_MAX);
   604 		}
   605 		m_params[m_curparam].pushedas = Param_String;
   606 	}
   607 
   608 	_Int_PushString((cell_t *)buffer, length, sz_flags, cp_flags);
   609 	m_curparam++;
   610 
   611 	return SP_ERROR_NONE;
   612 }
   613 
   614 void CForward::Cancel()
   615 {
   616 	if (!m_curparam)
   617 	{
   618 		return;
   619 	}
   620 
   621 	m_curparam = 0;
   622 	m_errstate = SP_ERROR_NONE;
   623 }
   624 
   625 bool CForward::AddFunction(IPluginContext *pContext, funcid_t index)
   626 {
   627 	IPluginFunction *pFunc = pContext->GetFunctionById(index);
   628 
   629 	if (!pFunc)
   630 	{
   631 		return false;
   632 	}
   633 
   634 	return AddFunction(pFunc);
   635 }
   636 
   637 bool CForward::RemoveFunction(IPluginContext *pContext, funcid_t index)
   638 {
   639 	IPluginFunction *pFunc = pContext->GetFunctionById(index);
   640 
   641 	if (!pFunc)
   642 	{
   643 		return false;
   644 	}
   645 
   646 	return RemoveFunction(pFunc);
   647 }
   648 
   649 bool CForward::RemoveFunction(IPluginFunction *func)
   650 {
   651 	bool found = false;
   652 	FuncIter iter;
   653 	List<IPluginFunction *> *lst;
   654 
   655 	if (func->IsRunnable())
   656 	{
   657 		lst = &m_functions;
   658 	} else {
   659 		lst = &m_paused;
   660 	}
   661 
   662 	for (iter=m_functions.begin(); iter!=m_functions.end(); iter++)
   663 	{
   664 		if ((*iter) == func)
   665 		{
   666 			found = true;
   667 			lst->erase(iter);
   668 			break;
   669 		}
   670 	}
   671 
   672 	/* Cancel a call, if any */
   673 	if (found || m_curparam)
   674 	{
   675 		func->Cancel();
   676 	}
   677 
   678 	return found;
   679 }
   680 
   681 unsigned int CForward::RemoveFunctionsOfPlugin(IPlugin *plugin)
   682 {
   683 	FuncIter iter;
   684 	IPluginFunction *func;
   685 	unsigned int removed = 0;
   686 	IPluginContext *pContext = plugin->GetBaseContext();
   687 	for (iter=m_functions.begin(); iter!=m_functions.end();)
   688 	{
   689 		func = (*iter);
   690 		if (func->GetParentContext() == pContext)
   691 		{
   692 			iter = m_functions.erase(iter);
   693 			removed++;
   694 		} else {
   695 			iter++;
   696 		}
   697 	}
   698 
   699 	return removed;
   700 }
   701 
   702 bool CForward::AddFunction(IPluginFunction *func)
   703 {
   704 	if (m_curparam)
   705 	{
   706 		return false;
   707 	}
   708 
   709 	if (func->IsRunnable())
   710 	{
   711 		m_functions.push_back(func);
   712 	} else {
   713 		m_paused.push_back(func);
   714 	}
   715 
   716 	return true;
   717 }
   718 
   719 const char *CForward::GetForwardName()
   720 {
   721 	return m_name;
   722 }
   723 
   724 unsigned int CForward::GetFunctionCount()
   725 {
   726 	return m_functions.size();
   727 }
   728 
   729 ExecType CForward::GetExecType()
   730 {
   731 	return m_ExecType;
   732 }