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