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