core/PluginSys.h
author Kyle Sanderson <kyle.leet@gmail.com>
Sun Mar 17 21:58:56 2013 +0000 (2013-03-17)
changeset 3837 f86a51ee4eb4
parent 3790 98b099a406d2
permissions -rw-r--r--
Check for cloned handles when dumping (bug 5245, r=asherkin).
     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 "sm_trie.h"
    47 #include "sourcemod.h"
    48 #include <IRootConsoleMenu.h>
    49 #if SOURCE_ENGINE >= SE_ALIENSWARM
    50 #include "convar_sm_swarm.h"
    51 #elif SOURCE_ENGINE >= SE_LEFT4DEAD
    52 #include "convar_sm_l4d.h"
    53 #elif SOURCE_ENGINE >= SE_ORANGEBOX
    54 #include "convar_sm_ob.h"
    55 #else
    56 #include "convar_sm.h"
    57 #endif
    58 #include "ITranslator.h"
    59 #include "IGameConfigs.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 enum LibraryAction
   134 {
   135 	LibraryAction_Removed,
   136 	LibraryAction_Added
   137 };
   138 
   139 struct AutoConfig
   140 {
   141 	String autocfg;
   142 	String folder;
   143 	bool create;
   144 };
   145 
   146 class CPlugin;
   147 
   148 class CPlugin : 
   149 	public IPlugin,
   150 	public CNativeOwner
   151 {
   152 	friend class CPluginManager;
   153 	friend class CFunction;
   154 public:
   155 	CPlugin(const char *file);
   156 	~CPlugin();
   157 public:
   158 	PluginType GetType();
   159 	SourcePawn::IPluginContext *GetBaseContext();
   160 	sp_context_t *GetContext();
   161 	void *GetPluginStructure();
   162 	const char *GetFilename();
   163 	bool IsDebugging();
   164 	PluginStatus GetStatus();
   165 	bool IsSilentlyFailed();
   166 	void SetSilentlyFailed(bool sf);
   167 	const sm_plugininfo_t *GetPublicInfo();
   168 	bool SetPauseState(bool paused);
   169 	unsigned int GetSerial();
   170 	IdentityToken_t *GetIdentity();
   171 	unsigned int CalcMemUsage();
   172 	bool SetProperty(const char *prop, void *ptr);
   173 	bool GetProperty(const char *prop, void **ptr, bool remove=false);
   174 	void DropEverything();
   175 	SourcePawn::IPluginRuntime *GetRuntime();
   176 public:
   177 	/**
   178 	 * Creates a plugin object with default values.
   179 	 *   If an error buffer is specified, and an error occurs, the error will be copied to the buffer
   180 	 * and NULL will be returned.
   181 	 *   If an error buffer is not specified, the error will be copied to an internal buffer and 
   182 	 * a valid (but error-stated) CPlugin will be returned.
   183 	 */
   184 	static CPlugin *CreatePlugin(const char *file, char *error, size_t maxlength);
   185 public:
   186 
   187 	/**
   188 	 * Sets an error state on the plugin
   189 	 */
   190 	void SetErrorState(PluginStatus status, const char *error_fmt, ...);
   191 
   192 	/**
   193 	 * Initializes the plugin's identity information
   194 	 */
   195 	void InitIdentity();
   196 
   197 	/**
   198 	 * Calls the OnPluginLoad function, and sets any failed states if necessary.
   199 	 * NOTE: Valid pre-states are: Plugin_Created
   200 	 * NOTE: If validated, plugin state is changed to Plugin_Loaded
   201 	 *
   202 	 * If the error buffer is NULL, the error message is cached locally.
   203 	 */
   204 	APLRes Call_AskPluginLoad(char *error, size_t maxlength);
   205 
   206 	/**
   207 	 * Calls the OnPluginStart function.
   208 	 * NOTE: Valid pre-states are: Plugin_Created
   209 	 * NOTE: Post-state will be Plugin_Running
   210 	 */
   211 	void Call_OnPluginStart();
   212 
   213 	/**
   214 	 * Calls the OnPluginEnd function.
   215 	 */
   216 	void Call_OnPluginEnd();
   217 
   218 	/**
   219 	 * Calls the OnAllPluginsLoaded function.
   220 	 */
   221 	void Call_OnAllPluginsLoaded();
   222 
   223 	/**
   224 	 * Returns true if a plugin is usable.
   225 	 */
   226 	bool IsRunnable();
   227 
   228 	/**
   229 	 * Get languages info.
   230 	 */
   231 	IPhraseCollection *GetPhrases();
   232 public:
   233 	/**
   234 	 * Returns the modification time during last plugin load.
   235 	 */
   236 	time_t GetTimeStamp();
   237 
   238 	/**
   239 	 * Returns the current modification time of the plugin file.
   240 	 */
   241 	time_t GetFileTimeStamp();
   242 
   243 	/** 
   244 	 * Returns true if the plugin was running, but is now invalid.
   245 	 */
   246 	bool WasRunning();
   247 
   248 	Handle_t GetMyHandle();
   249 
   250 	bool AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func);
   251 	void AddConfig(bool autoCreate, const char *cfg, const char *folder);
   252 	unsigned int GetConfigCount();
   253 	AutoConfig *GetConfig(unsigned int i);
   254 	inline void AddLibrary(const char *name)
   255 	{
   256 		m_Libraries.push_back(name);
   257 	}
   258 	void LibraryActions(LibraryAction action);
   259 	void SyncMaxClients(int max_clients);
   260 protected:
   261 	bool UpdateInfo();
   262 	void SetTimeStamp(time_t t);
   263 	void DependencyDropped(CPlugin *pOwner);
   264 private:
   265 	PluginType m_type;
   266 	char m_filename[PLATFORM_MAX_PATH];
   267 	PluginStatus m_status;
   268 	bool m_bSilentlyFailed;
   269 	unsigned int m_serial;
   270 	sm_plugininfo_t m_info;
   271 	char m_errormsg[256];
   272 	time_t m_LastAccess;
   273 	IdentityToken_t *m_ident;
   274 	Handle_t m_handle;
   275 	bool m_WasRunning;
   276 	IPhraseCollection *m_pPhrases;
   277 	List<String> m_RequiredLibs;
   278 	List<String> m_Libraries;
   279 	Trie *m_pProps;
   280 	bool m_FakeNativesMissing;
   281 	bool m_LibraryMissing;
   282 	CVector<AutoConfig *> m_configs;
   283 	bool m_bGotAllLoaded;
   284 	int m_FileVersion;
   285 	char m_DateTime[256];
   286 	IPluginRuntime *m_pRuntime;
   287 	IPluginContext *m_pContext;
   288 	sp_pubvar_t *m_MaxClientsVar;
   289 };
   290 
   291 class CPluginManager : 
   292 	public IPluginManager,
   293 	public SMGlobalClass,
   294 	public IHandleTypeDispatch,
   295 	public IRootConsoleCommand
   296 {
   297 	friend class CPlugin;
   298 public:
   299 	CPluginManager();
   300 	~CPluginManager();
   301 public:
   302 	/* Implements iterator class */
   303 	class CPluginIterator : public IPluginIterator
   304 	{
   305 	public:
   306 		CPluginIterator(List<CPlugin *> *mylist);
   307 		virtual ~CPluginIterator();
   308 		virtual bool MorePlugins();
   309 		virtual IPlugin *GetPlugin();
   310 		virtual void NextPlugin();
   311 		void Release();
   312 	public:
   313 		void Reset();
   314 	private:
   315 		List<CPlugin *> *mylist;
   316 		List<CPlugin *>::iterator current;
   317 	};
   318 	friend class CPluginManager::CPluginIterator;
   319 public: //IPluginManager
   320 	IPlugin *LoadPlugin(const char *path, 
   321 								bool debug,
   322 								PluginType type,
   323 								char error[],
   324 								size_t maxlength,
   325 								bool *wasloaded);
   326 	bool UnloadPlugin(IPlugin *plugin);
   327 	IPlugin *FindPluginByContext(const sp_context_t *ctx);
   328 	unsigned int GetPluginCount();
   329 	IPluginIterator *GetPluginIterator();
   330 	void AddPluginsListener(IPluginsListener *listener);
   331 	void RemovePluginsListener(IPluginsListener *listener);
   332 public: //SMGlobalClass
   333 	void OnSourceModAllInitialized();
   334 	void OnSourceModShutdown();
   335 	ConfigResult OnSourceModConfigChanged(const char *key, const char *value, ConfigSource source, char *error, size_t maxlength);
   336 	void OnSourceModMaxPlayersChanged(int newvalue);
   337 public: //IHandleTypeDispatch
   338 	void OnHandleDestroy(HandleType_t type, void *object);
   339 	bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize);
   340 public: //IRootConsoleCommand
   341 	void OnRootConsoleCommand(const char *cmdname, const CCommand &command);
   342 public:
   343 	/**
   344 	 * Loads all plugins not yet loaded
   345 	 */
   346 	void LoadAll_FirstPass(const char *config, const char *basedir);
   347 
   348 	/**
   349 	 * Runs the second loading pass for all plugins
   350 	 */
   351 	void LoadAll_SecondPass();
   352 
   353 	/**
   354 	 * Tests a plugin file mask against a local folder.
   355 	 * The alias is searched backwards from localdir - i.e., given this input:
   356 	 *   csdm/ban        csdm/ban
   357 	 *   ban             csdm/ban
   358 	 *   csdm/ban        optional/csdm/ban
   359 	 * All of these will return true for an alias match.  
   360 	 * Wildcards are allowed in the filename.
   361 	 */
   362 	bool TestAliasMatch(const char *alias, const char *localdir);
   363 
   364 	/** 
   365 	 * Returns whether anything loaded will be a late load.
   366 	 */
   367 	bool IsLateLoadTime() const;
   368 
   369 	/**
   370 	 * Converts a Handle to an IPlugin if possible.
   371 	 */
   372 	IPlugin *PluginFromHandle(Handle_t handle, HandleError *err);
   373 
   374 	/**
   375 	 * Finds a plugin based on its index. (starts on index 1)
   376 	 */
   377 	CPlugin *GetPluginByOrder(int num);
   378 
   379 	int GetOrderOfPlugin(IPlugin *pl);
   380 
   381 	/** 
   382 	 * Internal version of FindPluginByContext()
   383 	 */
   384 	CPlugin *GetPluginByCtx(const sp_context_t *ctx);
   385 
   386 	/**
   387 	 * Gets status text for a status code 
   388 	 */
   389 	const char *GetStatusText(PluginStatus status);
   390 
   391 	/**
   392 	* Reload or update plugins on level shutdown.
   393 	*/
   394 	void ReloadOrUnloadPlugins();
   395 
   396 	/**
   397 	 * Add public functions from all running or paused
   398 	 * plugins to the specified forward if the names match.
   399 	 */
   400 	void AddFunctionsToForward(const char *name, IChangeableForward *pForward);
   401 
   402 	/**
   403 	 * Iterates through plugins to call OnAllPluginsLoaded.
   404 	 */
   405 	void AllPluginsLoaded();
   406 
   407 	CPlugin *GetPluginFromIdentity(IdentityToken_t *pToken);
   408 
   409 	void Shutdown();
   410 
   411 	void OnLibraryAction(const char *lib, LibraryAction action);
   412 
   413 	bool LibraryExists(const char *lib);
   414 
   415 	bool ReloadPlugin(CPlugin *pl);
   416 
   417 	void UnloadAll();
   418 
   419 	CPlugin *FindPluginByConsoleArg(const char *arg);
   420 
   421 	void SyncMaxClients(int max_clients);
   422 
   423 	void ListPluginsToClient(CPlayer *player, const CCommand &args);
   424 private:
   425 	LoadRes _LoadPlugin(CPlugin **pPlugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength);
   426 
   427 	void LoadAutoPlugin(const char *plugin);
   428 
   429 	/**
   430 	 * Recursively loads all plugins in the given directory.
   431 	 */
   432 	void LoadPluginsFromDir(const char *basedir, const char *localdir);
   433 
   434 	/**
   435 	 * Adds a plugin object.  This is wrapped by LoadPlugin functions.
   436 	 */
   437 	void AddPlugin(CPlugin *pPlugin);
   438 
   439 	/**
   440 	 * Runs the second loading pass on a plugin.
   441 	 */
   442 	bool RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength);
   443 
   444 	/**
   445 	 * Runs an extension pass on a plugin.
   446 	 */
   447 	bool LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength);
   448 
   449 	/**
   450 	* Manages required natives.
   451 	*/
   452 	bool FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength);
   453 
   454 	void _SetPauseState(CPlugin *pPlugin, bool pause);
   455 protected:
   456 	/**
   457 	 * Caching internal objects
   458 	 */
   459 	void ReleaseIterator(CPluginIterator *iter);
   460 public:
   461 	inline IdentityToken_t *GetIdentity()
   462 	{
   463 		return m_MyIdent;
   464 	}
   465 private:
   466 	void TryRefreshDependencies(CPlugin *pOther);
   467 private:
   468 	List<IPluginsListener *> m_listeners;
   469 	List<CPlugin *> m_plugins;
   470 	CStack<CPluginManager::CPluginIterator *> m_iters;
   471 	Trie *m_LoadLookup;
   472 	bool m_AllPluginsLoaded;
   473 	IdentityToken_t *m_MyIdent;
   474 
   475 	/* Dynamic native stuff */
   476 	List<FakeNative *> m_Natives;
   477 
   478 	bool m_LoadingLocked;
   479 	
   480 	// Config
   481 	bool m_bBlockBadPlugins;
   482 	
   483 	// Forwards
   484 	IForward *m_pOnLibraryAdded;
   485 	IForward *m_pOnLibraryRemoved;
   486 };
   487 
   488 extern CPluginManager g_PluginSys;
   489 
   490 #endif //_INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
   491