3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
32 #ifndef _INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
33 #define _INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
38 #include <IPluginSys.h>
39 #include <IHandleSys.h>
40 #include <IForwardSys.h>
43 #include <sh_vector.h>
44 #include <sh_string.h>
45 #include "sm_globals.h"
46 #include "PluginInfoDatabase.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"
55 #include "convar_sm.h"
57 #include "ITranslator.h"
58 #include "NativeOwner.h"
63 using namespace SourceHook;
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.
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.
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.
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
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.
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.
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
118 LoadRes_AlreadyLoaded,
136 friend class CPluginManager;
137 friend class CFunction;
139 CPlugin(const char *file);
142 PluginType GetType();
143 SourcePawn::IPluginContext *GetBaseContext();
144 sp_context_t *GetContext();
145 void *GetPluginStructure();
146 const char *GetFilename();
148 PluginStatus GetStatus();
149 const sm_plugininfo_t *GetPublicInfo();
150 bool SetPauseState(bool paused);
151 unsigned int GetSerial();
152 IdentityToken_t *GetIdentity();
153 unsigned int CalcMemUsage();
154 bool SetProperty(const char *prop, void *ptr);
155 bool GetProperty(const char *prop, void **ptr, bool remove=false);
156 void DropEverything();
157 SourcePawn::IPluginRuntime *GetRuntime();
160 * Creates a plugin object with default values.
161 * If an error buffer is specified, and an error occurs, the error will be copied to the buffer
162 * and NULL will be returned.
163 * If an error buffer is not specified, the error will be copied to an internal buffer and
164 * a valid (but error-stated) CPlugin will be returned.
166 static CPlugin *CreatePlugin(const char *file, char *error, size_t maxlength);
170 * Sets an error state on the plugin
172 void SetErrorState(PluginStatus status, const char *error_fmt, ...);
175 * Initializes the plugin's identity information
180 * Calls the OnPluginLoad function, and sets any failed states if necessary.
181 * NOTE: Valid pre-states are: Plugin_Created
182 * NOTE: If validated, plugin state is changed to Plugin_Loaded
184 * If the error buffer is NULL, the error message is cached locally.
186 bool Call_AskPluginLoad(char *error, size_t maxlength);
189 * Calls the OnPluginStart function.
190 * NOTE: Valid pre-states are: Plugin_Created
191 * NOTE: Post-state will be Plugin_Running
193 void Call_OnPluginStart();
196 * Calls the OnPluginEnd function.
198 void Call_OnPluginEnd();
201 * Calls the OnAllPluginsLoaded function.
203 void Call_OnAllPluginsLoaded();
206 * Returns true if a plugin is usable.
211 * Get languages info.
213 IPhraseCollection *GetPhrases();
216 * Returns the modification time during last plugin load.
218 time_t GetTimeStamp();
221 * Returns the current modification time of the plugin file.
223 time_t GetFileTimeStamp();
226 * Returns true if the plugin was running, but is now invalid.
230 Handle_t GetMyHandle();
232 bool AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func);
233 void AddConfig(bool autoCreate, const char *cfg, const char *folder);
234 unsigned int GetConfigCount();
235 AutoConfig *GetConfig(unsigned int i);
236 inline void AddLibrary(const char *name)
238 m_Libraries.push_back(name);
240 void LibraryActions(bool dropping);
241 void SyncMaxClients(int max_clients);
244 void SetTimeStamp(time_t t);
245 void DependencyDropped(CPlugin *pOwner);
248 char m_filename[PLATFORM_MAX_PATH];
249 PluginStatus m_status;
250 unsigned int m_serial;
251 sm_plugininfo_t m_info;
252 char m_errormsg[256];
254 IdentityToken_t *m_ident;
257 IPhraseCollection *m_pPhrases;
258 List<String> m_RequiredLibs;
259 List<String> m_Libraries;
261 bool m_FakeNativesMissing;
262 bool m_LibraryMissing;
263 CVector<AutoConfig *> m_configs;
264 bool m_bGotAllLoaded;
266 char m_DateTime[256];
267 IPluginRuntime *m_pRuntime;
268 IPluginContext *m_pContext;
269 sp_pubvar_t *m_MaxClientsVar;
272 class CPluginManager :
273 public IPluginManager,
274 public SMGlobalClass,
275 public IHandleTypeDispatch,
276 public IRootConsoleCommand
278 friend class CPlugin;
283 /* Implements iterator class */
284 class CPluginIterator : public IPluginIterator
287 CPluginIterator(List<CPlugin *> *mylist);
288 virtual ~CPluginIterator();
289 virtual bool MorePlugins();
290 virtual IPlugin *GetPlugin();
291 virtual void NextPlugin();
296 List<CPlugin *> *mylist;
297 List<CPlugin *>::iterator current;
299 friend class CPluginManager::CPluginIterator;
300 public: //IPluginManager
301 IPlugin *LoadPlugin(const char *path,
307 bool UnloadPlugin(IPlugin *plugin);
308 IPlugin *FindPluginByContext(const sp_context_t *ctx);
309 unsigned int GetPluginCount();
310 IPluginIterator *GetPluginIterator();
311 void AddPluginsListener(IPluginsListener *listener);
312 void RemovePluginsListener(IPluginsListener *listener);
313 public: //SMGlobalClass
314 void OnSourceModAllInitialized();
315 void OnSourceModShutdown();
316 void OnSourceModMaxPlayersChanged(int newvalue);
317 public: //IHandleTypeDispatch
318 void OnHandleDestroy(HandleType_t type, void *object);
319 bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize);
320 public: //IRootConsoleCommand
321 void OnRootConsoleCommand(const char *cmdname, const CCommand &command);
324 * Loads all plugins not yet loaded
326 void LoadAll_FirstPass(const char *config, const char *basedir);
329 * Runs the second loading pass for all plugins
331 void LoadAll_SecondPass();
334 * Tests a plugin file mask against a local folder.
335 * The alias is searched backwards from localdir - i.e., given this input:
338 * csdm/ban optional/csdm/ban
339 * All of these will return true for an alias match.
340 * Wildcards are allowed in the filename.
342 bool TestAliasMatch(const char *alias, const char *localdir);
345 * Returns whether anything loaded will be a late load.
347 bool IsLateLoadTime() const;
350 * Converts a Handle to an IPlugin if possible.
352 IPlugin *PluginFromHandle(Handle_t handle, HandleError *err);
355 * Finds a plugin based on its index. (starts on index 1)
357 CPlugin *GetPluginByOrder(int num);
359 int GetOrderOfPlugin(IPlugin *pl);
362 * Internal version of FindPluginByContext()
364 CPlugin *GetPluginByCtx(const sp_context_t *ctx);
367 * Gets status text for a status code
369 const char *GetStatusText(PluginStatus status);
372 * Reload or update plugins on level shutdown.
374 void ReloadOrUnloadPlugins();
377 * Add public functions from all running or paused
378 * plugins to the specified forward if the names match.
380 void AddFunctionsToForward(const char *name, IChangeableForward *pForward);
383 * Iterates through plugins to call OnAllPluginsLoaded.
385 void AllPluginsLoaded();
387 CPlugin *GetPluginFromIdentity(IdentityToken_t *pToken);
391 void OnLibraryAction(const char *lib, bool is_a_plugin, bool drop);
393 bool LibraryExists(const char *lib);
395 bool ReloadPlugin(CPlugin *pl);
399 CPlugin *FindPluginByConsoleArg(const char *arg);
401 void SyncMaxClients(int max_clients);
403 void ListPluginsToClient(CPlayer *player, const CCommand &args);
405 LoadRes _LoadPlugin(CPlugin **pPlugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength);
407 void LoadAutoPlugin(const char *plugin);
410 * Recursively loads all plugins in the given directory.
412 void LoadPluginsFromDir(const char *basedir, const char *localdir);
415 * Adds a plugin object. This is wrapped by LoadPlugin functions.
417 void AddPlugin(CPlugin *pPlugin);
420 * Runs the second loading pass on a plugin.
422 bool RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength);
425 * Runs an extension pass on a plugin.
427 bool LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength);
430 * Manages required natives.
432 bool FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength);
434 void _SetPauseState(CPlugin *pPlugin, bool pause);
437 * Caching internal objects
439 void ReleaseIterator(CPluginIterator *iter);
441 inline IdentityToken_t *GetIdentity()
446 void TryRefreshDependencies(CPlugin *pOther);
448 List<IPluginsListener *> m_listeners;
449 List<CPlugin *> m_plugins;
450 CStack<CPluginManager::CPluginIterator *> m_iters;
451 CPluginInfoDatabase m_PluginInfo;
453 bool m_AllPluginsLoaded;
454 IdentityToken_t *m_MyIdent;
456 /* Dynamic native stuff */
457 List<FakeNative *> m_Natives;
459 bool m_LoadingLocked;
462 extern CPluginManager g_PluginSys;
464 #endif //_INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_