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