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