public/IForwardSys.h
author David Anderson <dvander@alliedmods.net>
Wed Sep 26 14:36:08 2007 +0000 (2007-09-26)
changeset 1487 810b3fc562cb
parent 1330 ab94316bb52b
child 1735 d6966e3316e9
permissions -rw-r--r--
updated sdk for more interfaces
     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 #ifndef _INCLUDE_SOURCEMOD_FORWARDINTERFACE_H_
    33 #define _INCLUDE_SOURCEMOD_FORWARDINTERFACE_H_
    34 
    35 /**
    36  * @file IForwardSys.h
    37  * @brief Defines the interface for managing collections ("forwards") of plugin calls.
    38  *
    39  *   The Forward System is responsible for managing automated collections of IPluginFunctions.  
    40  * It thus provides wrappers to calling many functions at once.  There are two types of such 
    41  * wrappers: Managed and Unmanaged.  Confusingly, these terms refer to whether the user manages
    42  * the forwards, not Core.  Managed forwards are completely managed by the user, and are custom
    43  * editable collections.  Unmanaged forwards are the opposite, and will only work on a single global
    44  * function name in all plugins.
    45  */
    46 
    47 #include <IPluginSys.h>
    48 #include <sp_vm_api.h>
    49 
    50 using namespace SourcePawn;
    51 
    52 #define SMINTERFACE_FORWARDMANAGER_NAME		"IForwardManager"
    53 #define SMINTERFACE_FORWARDMANAGER_VERSION	2
    54 
    55 /*
    56  * There is some very important documentation at the bottom of this file.
    57  * Readers interested in knowing more about the forward system, scrolling down is a must!
    58  */
    59 
    60 namespace SourceMod
    61 {
    62 	/**
    63 	 * @brief Defines the event hook result types plugins can return.
    64 	 */
    65 	enum ResultType
    66 	{
    67 		Pl_Continue = 0,	/**< No result */
    68 		Pl_Handled = 3,		/**< Result was handled, stop at the end */
    69 		Pl_Stop = 4,		/**< Result was handled, stop now */
    70 	};
    71 
    72 	/**
    73 	 * @brief Defines how a forward iterates through plugin functions.
    74 	 */
    75 	enum ExecType
    76 	{
    77 		ET_Ignore = 0,		/**< Ignore all return values, return 0 */
    78 		ET_Single = 1,		/**< Only return the last exec, ignore all others */
    79 		ET_Event = 2,		/**< Acts as an event with the ResultTypes above, no mid-Stops allowed, returns highest */
    80 		ET_Hook = 3,		/**< Acts as a hook with the ResultTypes above, mid-Stops allowed, returns highest */
    81 		ET_Custom = 4,		/**< Ignored or handled by an IForwardFilter */
    82 	};
    83 
    84 	class IForward;
    85 
    86 	/**
    87 	 * @brief Allows interception of how the Forward System executes functions.
    88 	 */
    89 	class IForwardFilter
    90 	{
    91 	public:
    92 		/**
    93 		 * @brief Called when an error occurs executing a plugin.
    94 		 *
    95 		 * @param fwd		IForward pointer.
    96 		 * @param func		IPluginFunction pointer to the failed function.
    97 		 * @param err		Error code.
    98 		 * @return			True to handle, false to pass to global error reporter.
    99 		 */
   100 		virtual bool OnErrorReport(IForward *fwd,
   101 									IPluginFunction *func,
   102 									int err)
   103 		{
   104 			return false;
   105 		}
   106 
   107 		/** 
   108 		 * @brief Called after each function return during execution.
   109 		 * NOTE: Only used for ET_Custom.
   110 		 *
   111 		 * @param fwd		IForward pointer.
   112 		 * @param func		IPluginFunction pointer to the executed function.
   113 		 * @param retval	Pointer to current return value (can be modified).
   114 		 * @return			ResultType denoting the next action to take.
   115 		 */
   116 		virtual ResultType OnFunctionReturn(IForward *fwd,
   117 									  IPluginFunction *func,
   118 									  cell_t *retval)
   119 		{
   120 			return Pl_Continue;
   121 		}
   122 
   123 		/** 
   124 		 * @brief Called when execution begins.
   125 		 */
   126 		virtual void OnExecuteBegin()
   127 		{
   128 		};
   129 
   130 		/**
   131 		 * @brief Called when execution ends.
   132 		 * 
   133 		 * @param final_ret	Final return value (modifiable).
   134 		 * @param success	Number of successful execs.
   135 		 * @param failed	Number of failed execs.
   136 		 */
   137 		virtual void OnExecuteEnd(cell_t *final_ret, unsigned int success, unsigned int failed)
   138 		{
   139 		}
   140 	};
   141 
   142 	/**
   143 	 * @brief Unmanaged Forward, abstracts calling multiple functions as "forwards," or collections of functions.
   144 	 * 
   145 	 *  Parameters should be pushed in forward order, unlike the virtual machine/IPluginContext order.
   146 	 * Some functions are repeated in here because their documentation differs from their IPluginFunction equivalents.
   147 	 * Missing are the Push functions, whose only doc change is that they throw SP_ERROR_PARAM on type mismatches.
   148 	 */
   149 	class IForward : public ICallable
   150 	{
   151 	public:
   152 		/** Virtual Destructor */
   153 		virtual ~IForward()
   154 		{
   155 		}
   156 	public:
   157 		/**
   158 		 * @brief Returns the name of the forward.
   159 		 *
   160 		 * @return			Forward name.
   161 		 */
   162 		virtual const char *GetForwardName() =0;
   163 
   164 		/**
   165 		 * @brief Returns the number of functions in this forward.
   166 		 *
   167 		 * @return			Number of functions in forward.
   168 		 */
   169 		virtual unsigned int GetFunctionCount() =0;
   170 
   171 		/**
   172 		 * @brief Returns the method of multi-calling this forward has.
   173 		 *
   174 		 * @return			ExecType of the forward.
   175 		 */
   176 		virtual ExecType GetExecType() =0;
   177 
   178 		/**
   179 		 * @brief Executes the forward.
   180 		 *
   181 		 * @param result		Optional pointer to store result in.
   182 		 * @param filter		Optional pointer to an IForwardFilter.
   183 		 * @return				Error code, if any.
   184 		 */
   185 		virtual int Execute(cell_t *result, IForwardFilter *filter=NULL) =0;
   186 
   187 		/**
   188 		 * @brief Pushes an array of cells onto the current call.  Different rules than ICallable.
   189 		 * NOTE: On Execute, the pointer passed will be modified according to the copyback rule.
   190 		 *
   191 		 * @param inarray	Array to copy.  Cannot be NULL, unlike ICallable's version.
   192 		 * @param cells		Number of cells to allocate and optionally read from the input array.
   193 		 * @param flags		Whether or not changes should be copied back to the input array.
   194 		 * @return			Error code, if any.
   195 		 */
   196 		virtual int PushArray(cell_t *inarray, unsigned int cells, int flags=0) =0;
   197 	};
   198 
   199 	/**
   200 	 * @brief Managed Forward, same as IForward, except the collection can be modified.
   201 	 */
   202 	class IChangeableForward : public IForward
   203 	{
   204 	public:
   205 		/** 
   206 		 * @brief Removes a function from the call list.
   207 		 * NOTE: Only removes one instance.
   208 		 *
   209 		 * @param func		Function to remove.
   210 		 * @return			Whether or not the function was removed.
   211 		 */
   212 		virtual bool RemoveFunction(IPluginFunction *func) =0;
   213 
   214 		/** 
   215 		 * @brief Removes all instances of a plugin from the call list.
   216 		 *
   217 		 * @param plugin	Plugin to remove instances of.
   218 		 * @return			Number of functions removed therein.
   219 		 */
   220 		virtual unsigned int RemoveFunctionsOfPlugin(IPlugin *plugin) =0;
   221 
   222 		/**
   223 		 * @brief Adds a function to the call list.
   224 		 * NOTE: Cannot be used during an incomplete call.
   225 		 * NOTE: If used during a call, function is temporarily queued until calls are over.
   226 		 * NOTE: Adding multiple copies of the same function is illegal.
   227 		 *
   228 		 * @param func		Function to add.
   229 		 * @return			True on success, otherwise false.
   230 		 */
   231 		virtual bool AddFunction(IPluginFunction *func) =0;
   232 
   233 		/**
   234 		 * @brief Adds a function to the call list.
   235 		 * NOTE: Cannot be used during an incomplete call.
   236 		 * NOTE: If used during a call, function is temporarily queued until calls are over.
   237 		 *
   238 		 * @param ctx		Context to use as a look-up.
   239 		 * @param index		Function id to add.
   240 		 * @return			True on success, otherwise false.
   241 		 */
   242 		virtual bool AddFunction(IPluginContext *ctx, funcid_t index) =0;
   243 
   244 		/** 
   245 		 * @brief Removes a function from the call list.
   246 		 * NOTE: Only removes one instance.
   247 		 *
   248 		 * @param ctx		Context to use as a look-up.
   249 		 * @param index		Function id to add.
   250 		 * @return			Whether or not the function was removed.
   251 		 */
   252 		virtual bool RemoveFunction(IPluginContext *ctx, funcid_t index) =0;
   253 	};
   254 
   255 	#define SP_PARAMTYPE_ANY	0
   256 	#define SP_PARAMFLAG_BYREF	(1<<0)
   257 	#define SP_PARAMTYPE_CELL	(1<<1)
   258 	#define SP_PARAMTYPE_FLOAT	(2<<1)
   259 	#define SP_PARAMTYPE_STRING	(3<<1)|SP_PARAMFLAG_BYREF
   260 	#define SP_PARAMTYPE_ARRAY	(4<<1)|SP_PARAMFLAG_BYREF
   261 	#define SP_PARAMTYPE_VARARG	(5<<1)
   262 
   263 	/**
   264 	 * @brief Describes the various ways to pass parameters to plugins.
   265 	 */
   266 	enum ParamType
   267 	{
   268 		Param_Any = SP_PARAMTYPE_ANY,				/**< Any data type can be pushed */
   269 		Param_Cell = SP_PARAMTYPE_CELL,				/**< Only basic cells can be pushed */
   270 		Param_Float = SP_PARAMTYPE_FLOAT,			/**< Only floats can be pushed */
   271 		Param_String = SP_PARAMTYPE_STRING,			/**< Only strings can be pushed */
   272 		Param_Array = SP_PARAMTYPE_ARRAY,			/**< Only arrays can be pushed */
   273 		Param_VarArgs = SP_PARAMTYPE_VARARG,		/**< Same as "..." in plugins, anything can be pushed, but it will always be byref */
   274 		Param_CellByRef = SP_PARAMTYPE_CELL|SP_PARAMFLAG_BYREF,		/**< Only a cell by reference can be pushed */
   275 		Param_FloatByRef = SP_PARAMTYPE_FLOAT|SP_PARAMFLAG_BYREF,	/**< Only a float by reference can be pushed */
   276 	};
   277 	
   278 	/**
   279 	 * @brief Provides functions for creating/destroying managed and unmanaged forwards.
   280 	 */
   281 	class IForwardManager : public SMInterface
   282 	{
   283 	public:
   284 		virtual const char *GetInterfaceName()
   285 		{
   286 			return SMINTERFACE_FORWARDMANAGER_NAME;
   287 		}
   288 		virtual unsigned int GetInterfaceVersion()
   289 		{
   290 			return SMINTERFACE_FORWARDMANAGER_VERSION;
   291 		}
   292 		virtual bool IsVersionCompatible(unsigned int version)
   293 		{
   294 			if (version < 2 || version > GetInterfaceVersion())
   295 			{
   296 				return false;
   297 			}
   298 			return true;
   299 		}
   300 	public:
   301 		/**
   302 		 * @brief Creates a managed forward.  This forward exists globally.
   303 		 *  The name used to create the forward is used as its public function in all target plugins.
   304 		 *  As new non-private plugins become loaded or unloaded, they will be automatically added
   305 		 * or removed.  This is ideal for global, static forwards that are never changed.
   306 		 *
   307 		 * @param name			Name of public function to use in forward.
   308 		 * @param et			Execution type to be used.
   309 		 * @param num_params	Number of parameter this function will have.
   310 		 *						NOTE: For varargs, this should include the vararg parameter.
   311 		 * @param types			Array of type information about each parameter.  If NULL, types
   312 		 *						are read off the vararg stream.
   313 		 * @param ...			If types is NULL, num_params ParamTypes should be pushed.
   314 		 * @return				A new IForward on success, NULL if type combination is impossible.
   315 		 */
   316 		virtual IForward *CreateForward(const char *name, 
   317 										ExecType et, 
   318 										unsigned int num_params, 
   319 										const ParamType *types, 
   320 										...) =0;
   321 
   322 		/**
   323 		 * @brief Creates an unmanaged forward.  This forward exists privately.
   324 		 * Unlike managed forwards, no functions are ever added by the Manager.
   325 		 * However, functions will be removed automatically if their parent plugin is unloaded.
   326 		 *
   327 		 * @param name			Name of forward (unused except for lookup, can be NULL for anonymous).
   328 		 * @param et			Execution type to be used.
   329 		 * @param num_params	Number of parameter this function will have.
   330 		 *						NOTE: For varargs, this should include the vararg parameter.
   331 		 * @param types			Array of type information about each parameter.  If NULL, types
   332 		 *						are read off the vararg stream.
   333 		 * @param ...			If types is NULL, num_params ParamTypes should be pushed.
   334 		 * @return				A new IChangeableForward on success, NULL if type combination is impossible.
   335 		 */
   336 		virtual IChangeableForward *CreateForwardEx(const char *name, 
   337 													ExecType et, 
   338 													int num_params, 
   339 													const ParamType *types, 
   340 													...) =0;
   341 
   342 		/**
   343 		 * @brief Finds a forward by name.  Does not return anonymous forwards (named NULL or "").
   344 		 *
   345 		 * @param name			Name of forward.
   346 		 * @param ifchng		Optionally store either NULL or an IChangeableForward pointer
   347 		 *                      depending on type of forward.
   348 		 * @return				IForward pointer, or NULL if none found matching the name.
   349 		 */
   350 		virtual IForward *FindForward(const char *name, IChangeableForward **ifchng) =0;
   351 
   352 		/**
   353 		 * @brief Frees and destroys a forward object.
   354 		 *
   355 		 * @param forward		An IForward created by CreateForward() or CreateForwardEx().
   356 		 */
   357 		virtual void ReleaseForward(IForward *forward) =0;
   358 	};
   359 }
   360 
   361 /*
   362  *  In the AMX Mod X model of forwarding, each forward contained a list of pairs, each pair containing
   363  * a function ID and an AMX structure.  The forward structure itself did very little but hold parameter types.
   364  * An execution call worked like this:
   365  *  - executeForward() took in a function id and a list of parameters
   366  *  - for each contained plugin:
   367  *   - the list of parameters was preprocessed and pushed
   368  *   - the call was made
   369  *   - the list was freed and copybacks were made
   370  *  - return
   371  * 
   372  *  The advantages to this is that the system is very easy to implement, and it's fast. The disadvantage is 
   373  * varargs tend to be very unforgiving and inflexible, and thus weird problems arose with casting.  You also 
   374  * lose flexibility, type checking, and the ability to reasonably use variable arguments lists in the VM.
   375  *
   376  *  SourceMod replaces this forward system with a far more advanced, but a bit bulkier one. The idea is that 
   377  * each plugin has a table of functions, and each function is an ICallable object.  As well as being an ICallable, 
   378  * each function is an IPluginFunction.  An ICallable simply describes the process of adding parameters to a 
   379  * function call.  An IPluginFunction describes the process of actually calling a function and performing allocation, 
   380  * copybacks, and deallocations.
   381  *
   382  * A very powerful forward system emerges: a Forward is just a collection of IPluginFunctions.  Thus, the same 
   383  * API can be easily wrapped around a simple list, and it will look transparent to the user.
   384  * Advantages:
   385  * 1) "SP Forwards" from AMX Mod X are simply IPluginFunctions without a collection.
   386  * 2) Forwards are function based, rather than plugin based, and are thus far more flexible at runtime..
   387  * 3) [2] Individual functions can be paused and more than one function from the same plugin can be hooked.
   388  * 4) [2] One hook type that used to map to many SP Forwards can now be centralized as one Forward.
   389  *    This helps alleviate messes like Fakemeta.
   390  * 5) Parameter pushing is type-checked and allows for variable arguments.
   391  *
   392  *  Note that while #2,3,4 could be added to AMX Mod X, the real binding property is #1, which makes the system
   393  * object oriented, rather than AMX Mod X, which hides the objects behind static functions.  It is entirely a design
   394  * issue, rather than a usability one.  The interesting part is when it gets to implementation, which has to cache
   395  * parameter pushing until execution.  Without this, multiple function calls can be started across one plugin, which
   396  * will result in heap corruption given SourcePawn's implementation.
   397  *
   398  * Observe the new calling process:
   399  * - Each parameter is pushed into a local cache using the ICallable interface.
   400  * - For each function in the collection:
   401  *  - Each parameter is decoded and -pushed into the function.
   402  *  - The call is made.
   403  * - Return
   404  *
   405  *  Astute readers will note the (minor) problems:
   406  * 1) More memory is used.  Specifically, rather than N params of memory, you now have N params * M plugins.
   407  *    This is because, again, parameters are cached both per-function and per-forward.
   408  * 2) There are slightly more calls going around: one extra call for each parameter, since each push is manual.
   409  *
   410  * HISTORICAL NOTES:
   411  *  There used to be a # about copy backs.  
   412  *  Note that originally, the Forward implementation was a thin wrapper around IForwards.  It did not cache pushes,
   413  * and instead immediately fired them to each internal plugin.  This was to allow users to know that pointers would 
   414  * be immediately resolved.  Unfortunately, this became extremely burdensome on the API and exposed many problems,
   415  * the major (and breaking) one was that two separate Function objects cannot be in a calling process on the same 
   416  * plugin at once. (:TODO: perhaps prevent that in the IPlugin object?) This is because heap functions lose their order
   417  * and become impossible to re-arrange without some global heap tracking mechanism.  It also made iterative copy backs 
   418  * for arrays/references overwhelmingly complex, since each plugin had to have its memory back-patched for each copy.
   419  *  Therefore, this was scrapped for cached parameters (current implementation), which is the implementation AMX Mod X 
   420  * uses.  It is both faster and works better.
   421  */
   422 
   423 #endif //_INCLUDE_SOURCEMOD_FORWARDINTERFACE_H_