core/PluginSys.h
author Nicholas Hastings <skamonkey@gmail.com>
Thu Mar 11 17:43:46 2010 -0500 (2010-03-11)
changeset 2937 f5016767bfdf
parent 2906 33cc9854bd97
child 3099 1b7bf8509625
permissions -rw-r--r--
Added missing core voting cvars to sourcemod.cfg (bug 4224, r=pred)
     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 #ifndef _INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
    33 #define _INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
    34 
    35 #include <time.h>
    36 #include <errno.h>
    37 #include <sys/stat.h>
    38 #include <IPluginSys.h>
    39 #include <IHandleSys.h>
    40 #include <IForwardSys.h>
    41 #include <sh_list.h>
    42 #include <sh_stack.h>
    43 #include <sh_vector.h>
    44 #include <sh_string.h>
    45 #include "sm_globals.h"
    46 #include "PluginInfoDatabase.h"
    47 #include "sm_trie.h"
    48 #include "sourcemod.h"
    49 #include <IRootConsoleMenu.h>
    50 #if (SOURCE_ENGINE == SE_LEFT4DEAD) || (SOURCE_ENGINE == SE_LEFT4DEAD2)
    51 #include "convar_sm_l4d.h"
    52 #elif (SOURCE_ENGINE == SE_ORANGEBOX) || (SOURCE_ENGINE == SE_ORANGEBOXVALVE)
    53 #include "convar_sm_ob.h"
    54 #else
    55 #include "convar_sm.h"
    56 #endif
    57 #include "ITranslator.h"
    58 #include "NativeOwner.h"
    59 #include "ShareSys.h"
    60 
    61 class CPlayer;
    62 
    63 using namespace SourceHook;
    64 
    65 /**
    66  * NOTES:
    67  *
    68  * UPDATE 2008-03-11: These comments are horribly out of date.  They paint a good overall 
    69  * picture of how PluginSys works, but things like dependencies and fake natives have 
    70  * complicated things quite a bit.
    71  *
    72  *  Currently this system needs a lot of work but it's good skeletally.  Plugin creation 
    73  * is done without actually compiling anything.  This is done by Load functions in the 
    74  * manager.  This will need a rewrite when we add context switching.
    75  *
    76  *  The plugin object itself has a few things to note.  The most important is that it stores
    77  * a table of function objects.  The manager marshals allocation and freeing of these objects.
    78  * The plugin object can be in erroneous states, they are:
    79  *   Plugin_Error   --> Some error occurred any time during or after compilation.
    80  *						This error can be cleared since the plugin itself is valid.
    81  *						However, the state itself being set prevents any runtime action.
    82  *   Plugin_BadLoad	--> The plugin failed to load entirely and nothing can be done to save it.
    83  *
    84  *  If a plugin fails to load externally, it is never added to the internal tracker.  However, 
    85  * plugins that failed to load from the internal loading mechanism are always tracked.  This 
    86  * allows users to see which automatically loaded plugins failed, and makes the interface a bit
    87  * more flexible.
    88  *
    89  *  Once a plugin is compiled, it sets its own state to Plugin_Created.  This state is still invalid
    90  * for execution.  SourceMod is a two pass system, and even though the second pass is not implemented
    91  * yet, it is structured so Plugin_Created must be switched to Plugin_Running in the second pass.  When
    92  * implemented, a Created plugin will be switched to Error in the second pass if it not loadable.
    93  *
    94  *  The two pass loading mechanism is described below.  Modules/natives are not implemented yet.
    95  * PASS ONE: All loadable plugins are found and have the following steps performed:
    96  *			 1.  Loading and compilation is attempted.
    97  *			 2.  If successful, all natives from Core are added.
    98  *			 3.  OnPluginLoad() is called.
    99  *			 4.  If failed, any user natives are scrapped and the process halts here.
   100  *			 5.  If successful, the plugin is ready for Pass 2.
   101  * INTERMEDIATE:
   102  *			 1.  All forced modules are loaded.
   103  * PASS TWO: All loaded plugins are found and have these steps performed:
   104  *			 1. Any modules referenced in the plugin that are not already loaded, are loaded.
   105  *			 2. If any module fails to load and the plugin requires it, load fails and jump to step 6.
   106  *			 3. If any natives are unresolved, check if they are found in the user-natives pool.
   107  *			 4. If yes, load succeeds.  If not, natives are passed through a native acceptance filter.
   108  *			 5. If the filter fails, the plugin is marked as failed.
   109  *			 6. If the plugin has failed to load at this point, any dynamic natives it has added are scrapped.
   110  *			    Furthermore, any plugin that referenced these natives must now have pass 2 re-ran.
   111  * PASS THREE (not a real pass):
   112  *			 7. Once all plugins are deemed to be loaded, OnPluginStart() is called
   113  */
   114 
   115 enum LoadRes
   116 {
   117 	LoadRes_Successful,
   118 	LoadRes_AlreadyLoaded,
   119 	LoadRes_Failure,
   120 	LoadRes_SilentFailure,
   121 	LoadRes_NeverLoad
   122 };
   123 
   124 enum APLRes
   125 {
   126 	APLRes_Success,
   127 	APLRes_Failure,
   128 	APLRes_SilentFailure
   129 };
   130 
   131 struct AutoConfig
   132 {
   133 	String autocfg;
   134 	String folder;
   135 	bool create;
   136 };
   137 
   138 class CPlugin;
   139 
   140 class CPlugin : 
   141 	public IPlugin,
   142 	public CNativeOwner
   143 {
   144 	friend class CPluginManager;
   145 	friend class CFunction;
   146 public:
   147 	CPlugin(const char *file);
   148 	~CPlugin();
   149 public:
   150 	PluginType GetType();
   151 	SourcePawn::IPluginContext *GetBaseContext();
   152 	sp_context_t *GetContext();
   153 	void *GetPluginStructure();
   154 	const char *GetFilename();
   155 	bool IsDebugging();
   156 	PluginStatus GetStatus();
   157 	bool IsSilentlyFailed();
   158 	void SetSilentlyFailed(bool sf);
   159 	const sm_plugininfo_t *GetPublicInfo();
   160 	bool SetPauseState(bool paused);
   161 	unsigned int GetSerial();
   162 	IdentityToken_t *GetIdentity();
   163 	unsigned int CalcMemUsage();
   164 	bool SetProperty(const char *prop, void *ptr);
   165 	bool GetProperty(const char *prop, void **ptr, bool remove=false);
   166 	void DropEverything();
   167 	SourcePawn::IPluginRuntime *GetRuntime();
   168 public:
   169 	/**
   170 	 * Creates a plugin object with default values.
   171 	 *   If an error buffer is specified, and an error occurs, the error will be copied to the buffer
   172 	 * and NULL will be returned.
   173 	 *   If an error buffer is not specified, the error will be copied to an internal buffer and 
   174 	 * a valid (but error-stated) CPlugin will be returned.
   175 	 */
   176 	static CPlugin *CreatePlugin(const char *file, char *error, size_t maxlength);
   177 public:
   178 
   179 	/**
   180 	 * Sets an error state on the plugin
   181 	 */
   182 	void SetErrorState(PluginStatus status, const char *error_fmt, ...);
   183 
   184 	/**
   185 	 * Initializes the plugin's identity information
   186 	 */
   187 	void InitIdentity();
   188 
   189 	/**
   190 	 * Calls the OnPluginLoad function, and sets any failed states if necessary.
   191 	 * NOTE: Valid pre-states are: Plugin_Created
   192 	 * NOTE: If validated, plugin state is changed to Plugin_Loaded
   193 	 *
   194 	 * If the error buffer is NULL, the error message is cached locally.
   195 	 */
   196 	APLRes Call_AskPluginLoad(char *error, size_t maxlength);
   197 
   198 	/**
   199 	 * Calls the OnPluginStart function.
   200 	 * NOTE: Valid pre-states are: Plugin_Created
   201 	 * NOTE: Post-state will be Plugin_Running
   202 	 */
   203 	void Call_OnPluginStart();
   204 
   205 	/**
   206 	 * Calls the OnPluginEnd function.
   207 	 */
   208 	void Call_OnPluginEnd();
   209 
   210 	/**
   211 	 * Calls the OnAllPluginsLoaded function.
   212 	 */
   213 	void Call_OnAllPluginsLoaded();
   214 
   215 	/**
   216 	 * Returns true if a plugin is usable.
   217 	 */
   218 	bool IsRunnable();
   219 
   220 	/**
   221 	 * Get languages info.
   222 	 */
   223 	IPhraseCollection *GetPhrases();
   224 public:
   225 	/**
   226 	 * Returns the modification time during last plugin load.
   227 	 */
   228 	time_t GetTimeStamp();
   229 
   230 	/**
   231 	 * Returns the current modification time of the plugin file.
   232 	 */
   233 	time_t GetFileTimeStamp();
   234 
   235 	/** 
   236 	 * Returns true if the plugin was running, but is now invalid.
   237 	 */
   238 	bool WasRunning();
   239 
   240 	Handle_t GetMyHandle();
   241 
   242 	bool AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func);
   243 	void AddConfig(bool autoCreate, const char *cfg, const char *folder);
   244 	unsigned int GetConfigCount();
   245 	AutoConfig *GetConfig(unsigned int i);
   246 	inline void AddLibrary(const char *name)
   247 	{
   248 		m_Libraries.push_back(name);
   249 	}
   250 	void LibraryActions(bool dropping);
   251 	void SyncMaxClients(int max_clients);
   252 protected:
   253 	bool UpdateInfo();
   254 	void SetTimeStamp(time_t t);
   255 	void DependencyDropped(CPlugin *pOwner);
   256 private:
   257 	PluginType m_type;
   258 	char m_filename[PLATFORM_MAX_PATH];
   259 	PluginStatus m_status;
   260 	bool m_bSilentlyFailed;
   261 	unsigned int m_serial;
   262 	sm_plugininfo_t m_info;
   263 	char m_errormsg[256];
   264 	time_t m_LastAccess;
   265 	IdentityToken_t *m_ident;
   266 	Handle_t m_handle;
   267 	bool m_WasRunning;
   268 	IPhraseCollection *m_pPhrases;
   269 	List<String> m_RequiredLibs;
   270 	List<String> m_Libraries;
   271 	Trie *m_pProps;
   272 	bool m_FakeNativesMissing;
   273 	bool m_LibraryMissing;
   274 	CVector<AutoConfig *> m_configs;
   275 	bool m_bGotAllLoaded;
   276 	int m_FileVersion;
   277 	char m_DateTime[256];
   278 	IPluginRuntime *m_pRuntime;
   279 	IPluginContext *m_pContext;
   280 	sp_pubvar_t *m_MaxClientsVar;
   281 };
   282 
   283 class CPluginManager : 
   284 	public IPluginManager,
   285 	public SMGlobalClass,
   286 	public IHandleTypeDispatch,
   287 	public IRootConsoleCommand
   288 {
   289 	friend class CPlugin;
   290 public:
   291 	CPluginManager();
   292 	~CPluginManager();
   293 public:
   294 	/* Implements iterator class */
   295 	class CPluginIterator : public IPluginIterator
   296 	{
   297 	public:
   298 		CPluginIterator(List<CPlugin *> *mylist);
   299 		virtual ~CPluginIterator();
   300 		virtual bool MorePlugins();
   301 		virtual IPlugin *GetPlugin();
   302 		virtual void NextPlugin();
   303 		void Release();
   304 	public:
   305 		void Reset();
   306 	private:
   307 		List<CPlugin *> *mylist;
   308 		List<CPlugin *>::iterator current;
   309 	};
   310 	friend class CPluginManager::CPluginIterator;
   311 public: //IPluginManager
   312 	IPlugin *LoadPlugin(const char *path, 
   313 								bool debug,
   314 								PluginType type,
   315 								char error[],
   316 								size_t maxlength,
   317 								bool *wasloaded);
   318 	bool UnloadPlugin(IPlugin *plugin);
   319 	IPlugin *FindPluginByContext(const sp_context_t *ctx);
   320 	unsigned int GetPluginCount();
   321 	IPluginIterator *GetPluginIterator();
   322 	void AddPluginsListener(IPluginsListener *listener);
   323 	void RemovePluginsListener(IPluginsListener *listener);
   324 public: //SMGlobalClass
   325 	void OnSourceModAllInitialized();
   326 	void OnSourceModShutdown();
   327 	void OnSourceModMaxPlayersChanged(int newvalue);
   328 public: //IHandleTypeDispatch
   329 	void OnHandleDestroy(HandleType_t type, void *object);
   330 	bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize);
   331 public: //IRootConsoleCommand
   332 	void OnRootConsoleCommand(const char *cmdname, const CCommand &command);
   333 public:
   334 	/**
   335 	 * Loads all plugins not yet loaded
   336 	 */
   337 	void LoadAll_FirstPass(const char *config, const char *basedir);
   338 
   339 	/**
   340 	 * Runs the second loading pass for all plugins
   341 	 */
   342 	void LoadAll_SecondPass();
   343 
   344 	/**
   345 	 * Tests a plugin file mask against a local folder.
   346 	 * The alias is searched backwards from localdir - i.e., given this input:
   347 	 *   csdm/ban        csdm/ban
   348 	 *   ban             csdm/ban
   349 	 *   csdm/ban        optional/csdm/ban
   350 	 * All of these will return true for an alias match.  
   351 	 * Wildcards are allowed in the filename.
   352 	 */
   353 	bool TestAliasMatch(const char *alias, const char *localdir);
   354 
   355 	/** 
   356 	 * Returns whether anything loaded will be a late load.
   357 	 */
   358 	bool IsLateLoadTime() const;
   359 
   360 	/**
   361 	 * Converts a Handle to an IPlugin if possible.
   362 	 */
   363 	IPlugin *PluginFromHandle(Handle_t handle, HandleError *err);
   364 
   365 	/**
   366 	 * Finds a plugin based on its index. (starts on index 1)
   367 	 */
   368 	CPlugin *GetPluginByOrder(int num);
   369 
   370 	int GetOrderOfPlugin(IPlugin *pl);
   371 
   372 	/** 
   373 	 * Internal version of FindPluginByContext()
   374 	 */
   375 	CPlugin *GetPluginByCtx(const sp_context_t *ctx);
   376 
   377 	/**
   378 	 * Gets status text for a status code 
   379 	 */
   380 	const char *GetStatusText(PluginStatus status);
   381 
   382 	/**
   383 	* Reload or update plugins on level shutdown.
   384 	*/
   385 	void ReloadOrUnloadPlugins();
   386 
   387 	/**
   388 	 * Add public functions from all running or paused
   389 	 * plugins to the specified forward if the names match.
   390 	 */
   391 	void AddFunctionsToForward(const char *name, IChangeableForward *pForward);
   392 
   393 	/**
   394 	 * Iterates through plugins to call OnAllPluginsLoaded.
   395 	 */
   396 	void AllPluginsLoaded();
   397 
   398 	CPlugin *GetPluginFromIdentity(IdentityToken_t *pToken);
   399 
   400 	void Shutdown();
   401 
   402 	void OnLibraryAction(const char *lib, bool is_a_plugin, bool drop);
   403 
   404 	bool LibraryExists(const char *lib);
   405 
   406 	bool ReloadPlugin(CPlugin *pl);
   407 
   408 	void UnloadAll();
   409 
   410 	CPlugin *FindPluginByConsoleArg(const char *arg);
   411 
   412 	void SyncMaxClients(int max_clients);
   413 
   414 	void ListPluginsToClient(CPlayer *player, const CCommand &args);
   415 private:
   416 	LoadRes _LoadPlugin(CPlugin **pPlugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength);
   417 
   418 	void LoadAutoPlugin(const char *plugin);
   419 
   420 	/**
   421 	 * Recursively loads all plugins in the given directory.
   422 	 */
   423 	void LoadPluginsFromDir(const char *basedir, const char *localdir);
   424 
   425 	/**
   426 	 * Adds a plugin object.  This is wrapped by LoadPlugin functions.
   427 	 */
   428 	void AddPlugin(CPlugin *pPlugin);
   429 
   430 	/**
   431 	 * Runs the second loading pass on a plugin.
   432 	 */
   433 	bool RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength);
   434 
   435 	/**
   436 	 * Runs an extension pass on a plugin.
   437 	 */
   438 	bool LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength);
   439 
   440 	/**
   441 	* Manages required natives.
   442 	*/
   443 	bool FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength);
   444 
   445 	void _SetPauseState(CPlugin *pPlugin, bool pause);
   446 protected:
   447 	/**
   448 	 * Caching internal objects
   449 	 */
   450 	void ReleaseIterator(CPluginIterator *iter);
   451 public:
   452 	inline IdentityToken_t *GetIdentity()
   453 	{
   454 		return m_MyIdent;
   455 	}
   456 private:
   457 	void TryRefreshDependencies(CPlugin *pOther);
   458 private:
   459 	List<IPluginsListener *> m_listeners;
   460 	List<CPlugin *> m_plugins;
   461 	CStack<CPluginManager::CPluginIterator *> m_iters;
   462 	CPluginInfoDatabase m_PluginInfo;
   463 	Trie *m_LoadLookup;
   464 	bool m_AllPluginsLoaded;
   465 	IdentityToken_t *m_MyIdent;
   466 
   467 	/* Dynamic native stuff */
   468 	List<FakeNative *> m_Natives;
   469 
   470 	bool m_LoadingLocked;
   471 };
   472 
   473 extern CPluginManager g_PluginSys;
   474 
   475 #endif //_INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
   476