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>.
33 #include "PluginSys.h"
35 #include "LibrarySys.h"
36 #include "HandleSys.h"
37 #include "ForwardSys.h"
38 #include "sourcemm_api.h"
39 #include "sourcemod.h"
40 #include "TextParsers.h"
42 #include "ExtensionSys.h"
43 #include "sm_srvcmds.h"
44 #include "sm_stringutil.h"
45 #include "ConCmdManager.h"
46 #include "PlayerManager.h"
47 #include "CoreConfig.h"
48 #include "Translator.h"
50 CPluginManager g_PluginSys;
51 HandleType_t g_PluginType = 0;
52 IdentityType_t g_PluginIdent = 0;
54 CPlugin::CPlugin(const char *file)
56 static int MySerial = 0;
58 m_type = PluginType_Private;
59 m_status = Plugin_Uncompiled;
60 m_bSilentlyFailed = false;
61 m_serial = ++MySerial;
63 m_errormsg[256] = '\0';
64 snprintf(m_filename, sizeof(m_filename), "%s", file);
67 m_pProps = sm_trie_create();
68 m_FakeNativesMissing = false;
69 m_LibraryMissing = false;
70 m_bGotAllLoaded = false;
71 m_pPhrases = g_Translator.CreatePhraseCollection();
72 m_MaxClientsVar = NULL;
80 sec.pOwner = g_PluginSys.GetIdentity();
81 sec.pIdentity = sec.pOwner;
83 g_HandleSys.FreeHandle(m_handle, &sec);
84 g_ShareSys.DestroyIdentity(m_ident);
87 if (m_pRuntime != NULL)
95 sm_trie_destroy(m_pProps);
97 for (size_t i=0; i<m_configs.size(); i++)
102 if (m_pPhrases != NULL)
104 m_pPhrases->Destroy();
109 void CPlugin::InitIdentity()
113 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
114 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
115 m_pRuntime->GetDefaultContext()->SetKey(1, m_ident);
116 m_pRuntime->GetDefaultContext()->SetKey(2, (IPlugin *)this);
120 unsigned int CPlugin::CalcMemUsage()
122 unsigned int base_size =
124 + sizeof(IdentityToken_t)
125 + (m_configs.size() * (sizeof(AutoConfig *) + sizeof(AutoConfig)))
126 + sm_trie_mem_usage(m_pProps);
128 for (unsigned int i = 0; i < m_configs.size(); i++)
130 base_size += m_configs[i]->autocfg.size();
131 base_size += m_configs[i]->folder.size();
134 for (List<String>::iterator i = m_Libraries.begin();
135 i != m_Libraries.end();
138 base_size += (*i).size();
141 for (List<String>::iterator i = m_RequiredLibs.begin();
142 i != m_RequiredLibs.end();
145 base_size += (*i).size();
151 Handle_t CPlugin::GetMyHandle()
156 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
158 char fullpath[PLATFORM_MAX_PATH];
159 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
160 FILE *fp = fopen(fullpath, "rb");
162 CPlugin *pPlugin = new CPlugin(file);
168 snprintf(error, maxlength, "Unable to open file");
170 pPlugin->m_status = Plugin_BadLoad;
179 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
181 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
183 if (exists && remove)
185 sm_trie_delete(m_pProps, prop);
191 bool CPlugin::SetProperty(const char *prop, void *ptr)
193 return sm_trie_insert(m_pProps, prop, ptr);
196 IPluginRuntime *CPlugin::GetRuntime()
201 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
203 PluginStatus old_status = m_status;
206 if (old_status == Plugin_Running)
208 /* Tell everyone we're now paused */
209 g_PluginSys._SetPauseState(this, true);
213 va_start(ap, error_fmt);
214 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
217 if (m_pRuntime != NULL)
219 m_pRuntime->SetPauseState(true);
223 bool CPlugin::UpdateInfo()
225 /* Now grab the info */
227 IPluginContext *base = GetBaseContext();
228 int err = base->FindPubvarByName("myinfo", &idx);
230 memset(&m_info, 0, sizeof(m_info));
232 if (err == SP_ERROR_NONE)
234 struct sm_plugininfo_c_t
242 sm_plugininfo_c_t *cinfo;
245 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
246 base->LocalToString(cinfo->name, (char **)&m_info.name);
247 base->LocalToString(cinfo->description, (char **)&m_info.description);
248 base->LocalToString(cinfo->author, (char **)&m_info.author);
249 base->LocalToString(cinfo->url, (char **)&m_info.url);
250 base->LocalToString(cinfo->version, (char **)&m_info.version);
253 m_info.author = m_info.author ? m_info.author : "";
254 m_info.description = m_info.description ? m_info.description : "";
255 m_info.name = m_info.name ? m_info.name : "";
256 m_info.url = m_info.url ? m_info.url : "";
257 m_info.version = m_info.version ? m_info.version : "";
259 if ((err = base->FindPubvarByName("__version", &idx)) == SP_ERROR_NONE)
261 struct __version_info
268 __version_info *info;
270 const char *pDate, *pTime, *pFileVers;
275 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&info);
276 m_FileVersion = info->version;
277 if (m_FileVersion >= 4)
279 base->LocalToString(info->date, (char **)&pDate);
280 base->LocalToString(info->time, (char **)&pTime);
281 UTIL_Format(m_DateTime, sizeof(m_DateTime), "%s %s", pDate, pTime);
283 if (m_FileVersion > 5)
285 base->LocalToString(info->filevers, (char **)&pFileVers);
286 SetErrorState(Plugin_Failed, "Newer SourceMod required (%s or higher)", pFileVers);
295 if ((err = base->FindPubvarByName("MaxClients", &idx)) == SP_ERROR_NONE)
297 base->GetPubvarByIndex(idx, &m_MaxClientsVar);
303 void CPlugin::SyncMaxClients(int max_clients)
305 if (m_MaxClientsVar == NULL)
310 *m_MaxClientsVar->offs = max_clients;
313 void CPlugin::Call_OnPluginStart()
315 if (m_status != Plugin_Loaded)
320 m_status = Plugin_Running;
322 SyncMaxClients(g_Players.MaxClients());
325 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginStart");
332 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
334 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
338 void CPlugin::Call_OnPluginEnd()
340 if (m_status > Plugin_Paused)
346 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginEnd");
352 pFunction->Execute(&result);
355 void CPlugin::Call_OnAllPluginsLoaded()
357 if (m_status > Plugin_Paused)
367 m_bGotAllLoaded = true;
370 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnAllPluginsLoaded");
371 if (pFunction != NULL)
373 pFunction->Execute(&result);
378 if ((pFunction = m_pRuntime->GetFunctionByName("OnMapStart")) != NULL)
380 pFunction->Execute(NULL);
384 if (SM_AreConfigsExecuted())
386 SM_ExecuteForPlugin(GetBaseContext());
390 APLRes CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
392 if (m_status != Plugin_Created)
394 return APLRes_Failure;
397 m_status = Plugin_Loaded;
401 bool haveNewAPL = false;
402 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad2");
408 else if (!(pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad")))
410 return APLRes_Success;
413 pFunction->PushCell(m_handle);
414 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
415 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
416 pFunction->PushCell(maxlength);
417 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
419 return APLRes_Failure;
424 return (APLRes)result;
428 return APLRes_Success;
432 return APLRes_Failure;
436 void *CPlugin::GetPluginStructure()
441 IPluginContext *CPlugin::GetBaseContext()
443 if (m_pRuntime == NULL)
448 return m_pRuntime->GetDefaultContext();
451 sp_context_t *CPlugin::GetContext()
456 const char *CPlugin::GetFilename()
461 PluginType CPlugin::GetType()
466 const sm_plugininfo_t *CPlugin::GetPublicInfo()
468 if (GetStatus() >= Plugin_Created)
475 unsigned int CPlugin::GetSerial()
480 PluginStatus CPlugin::GetStatus()
485 bool CPlugin::IsSilentlyFailed()
487 return m_bSilentlyFailed;
490 bool CPlugin::IsDebugging()
492 if (m_pRuntime == NULL)
500 void CPlugin::SetSilentlyFailed(bool sf)
502 m_bSilentlyFailed = sf;
505 void CPlugin::LibraryActions(bool dropping)
507 List<String>::iterator iter;
508 for (iter = m_Libraries.begin();
509 iter != m_Libraries.end();
512 g_PluginSys.OnLibraryAction((*iter).c_str(), true, dropping);
516 bool CPlugin::SetPauseState(bool paused)
518 if (paused && GetStatus() != Plugin_Running)
521 } else if (!paused && GetStatus() != Plugin_Paused) {
527 LibraryActions(true);
530 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginPauseChange");
534 pFunction->PushCell(paused ? 1 : 0);
535 pFunction->Execute(&result);
540 m_status = Plugin_Paused;
541 m_pRuntime->SetPauseState(true);
543 m_status = Plugin_Running;
544 m_pRuntime->SetPauseState(false);
547 g_PluginSys._SetPauseState(this, paused);
551 LibraryActions(false);
557 IdentityToken_t *CPlugin::GetIdentity()
562 bool CPlugin::IsRunnable()
564 return (m_status <= Plugin_Paused) ? true : false;
567 time_t CPlugin::GetFileTimeStamp()
569 char path[PLATFORM_MAX_PATH];
570 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
571 #ifdef PLATFORM_WINDOWS
573 if (_stat(path, &s) != 0)
574 #elif defined PLATFORM_POSIX
576 if (stat(path, &s) != 0)
587 time_t CPlugin::GetTimeStamp()
592 void CPlugin::SetTimeStamp(time_t t)
597 IPhraseCollection *CPlugin::GetPhrases()
602 void CPlugin::DependencyDropped(CPlugin *pOwner)
609 List<String>::iterator reqlib_iter;
610 List<String>::iterator lib_iter;
611 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
613 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
615 if ((*reqlib_iter) == (*lib_iter))
617 m_LibraryMissing = true;
622 List<NativeEntry *>::iterator iter;
623 NativeEntry *pNative;
626 unsigned int unbound = 0;
628 for (iter = pOwner->m_Natives.begin();
629 iter != pOwner->m_Natives.end();
633 /* Find this native! */
634 if (m_pRuntime->FindNativeByName(pNative->name, &idx) != SP_ERROR_NONE)
639 m_pRuntime->GetNativeByIndex(idx, &native);
641 native->status = SP_NATIVE_UNBOUND;
647 m_FakeNativesMissing = true;
650 /* :IDEA: in the future, add native trapping? */
651 if (m_FakeNativesMissing || m_LibraryMissing)
653 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
657 unsigned int CPlugin::GetConfigCount()
659 return (unsigned int)m_configs.size();
662 AutoConfig *CPlugin::GetConfig(unsigned int i)
664 if (i >= GetConfigCount())
672 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
674 /* Do a check for duplicates to prevent double-execution */
675 for (size_t i = 0; i < m_configs.size(); i++)
677 if (m_configs[i]->autocfg.compare(cfg) == 0
678 && m_configs[i]->folder.compare(folder) == 0
679 && m_configs[i]->create == autoCreate)
685 AutoConfig *c = new AutoConfig;
689 c->create = autoCreate;
691 m_configs.push_back(c);
694 void CPlugin::DropEverything()
697 List<CPlugin *>::iterator iter;
698 List<WeakNative>::iterator wk_iter;
700 /* Tell everyone that depends on us that we're about to drop */
701 for (iter = m_Dependents.begin();
702 iter != m_Dependents.end();
706 pOther->DependencyDropped(this);
709 /* Note: we don't care about things we depend on.
710 * The reason is that extensions have their own cleanup
711 * code for plugins. Although the "right" design would be
712 * to centralize that here, i'm omitting it for now. Thus,
713 * the code below to walk the plugins list will suffice.
716 /* Other plugins could be holding weak references that were
717 * added by us. We need to clean all of those up now.
719 for (iter = g_PluginSys.m_plugins.begin();
720 iter != g_PluginSys.m_plugins.end();
723 (*iter)->DropRefsTo(this);
726 /* Proceed with the rest of the necessities. */
727 CNativeOwner::DropEverything();
730 bool CPlugin::AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func)
734 if ((pEntry = g_ShareSys.AddFakeNative(pFunc, name, func)) == NULL)
739 m_Natives.push_back(pEntry);
748 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
754 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
759 bool CPluginManager::CPluginIterator::MorePlugins()
761 return (current != mylist->end());
764 void CPluginManager::CPluginIterator::NextPlugin()
769 void CPluginManager::CPluginIterator::Release()
771 g_PluginSys.ReleaseIterator(this);
774 CPluginManager::CPluginIterator::~CPluginIterator()
778 void CPluginManager::CPluginIterator::Reset()
780 current = mylist->begin();
787 CPluginManager::CPluginManager()
789 m_LoadLookup = sm_trie_create();
790 m_AllPluginsLoaded = false;
792 m_LoadingLocked = false;
795 CPluginManager::~CPluginManager()
798 * Ignore the fact that there might be plugins in the cache.
799 * This usually means that Core is not being unloaded properly, and everything
800 * will crash anyway. YAY
802 sm_trie_destroy(m_LoadLookup);
804 CStack<CPluginManager::CPluginIterator *>::iterator iter;
805 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
812 void CPluginManager::Shutdown()
814 List<CPlugin *>::iterator iter;
816 while ((iter = m_plugins.begin()) != m_plugins.end())
822 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
824 /* First read in the database of plugin settings */
827 m_AllPluginsLoaded = false;
828 if ((err=textparsers->ParseFile_SMC(config, &m_PluginInfo, &states)) != SMCError_Okay)
830 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
831 const char *err_msg = textparsers->GetSMCErrorString(err);
834 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
838 LoadPluginsFromDir(basedir, NULL);
841 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
843 char base_path[PLATFORM_MAX_PATH];
845 /* Form the current path to start reading from */
846 if (localpath == NULL)
848 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
850 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
853 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
858 g_LibSys.GetPlatformError(error, sizeof(error));
859 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
860 g_Logger.LogError("[SM] Platform returned error: %s", error);
864 while (dir->MoreFiles())
866 if (dir->IsEntryDirectory()
867 && (strcmp(dir->GetEntryName(), ".") != 0)
868 && (strcmp(dir->GetEntryName(), "..") != 0)
869 && (strcmp(dir->GetEntryName(), "disabled") != 0)
870 && (strcmp(dir->GetEntryName(), "optional") != 0))
872 char new_local[PLATFORM_MAX_PATH];
873 if (localpath == NULL)
875 /* If no path yet, don't add a former slash */
876 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
878 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
880 LoadPluginsFromDir(basedir, new_local);
881 } else if (dir->IsEntryFile()) {
882 const char *name = dir->GetEntryName();
883 size_t len = strlen(name);
885 && strcmp(&name[len-4], ".smx") == 0)
887 /* If the filename matches, load the plugin */
888 char plugin[PLATFORM_MAX_PATH];
889 if (localpath == NULL)
891 snprintf(plugin, sizeof(plugin), "%s", name);
893 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
895 LoadAutoPlugin(plugin);
900 g_LibSys.CloseDirectory(dir);
903 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
907 return LoadRes_NeverLoad;
911 bool no_load = false;
912 PluginSettings *pset;
913 unsigned int setcount = m_PluginInfo.GetSettingsNum();
914 for (unsigned int i=0; i<setcount; i++)
916 if ((pset = m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
920 if (pset->blockload_val)
928 * Does this plugin already exist?
931 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
933 /* Check to see if we should try reloading it */
934 if (pPlugin->GetStatus() == Plugin_BadLoad
935 || pPlugin->GetStatus() == Plugin_Error
936 || pPlugin->GetStatus() == Plugin_Failed
939 UnloadPlugin(pPlugin);
947 return LoadRes_AlreadyLoaded;
953 return LoadRes_NeverLoad;
956 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
958 assert(pPlugin != NULL);
960 pPlugin->m_type = PluginType_MapUpdated;
962 ICompilation *co = NULL;
964 if (pPlugin->m_status == Plugin_Uncompiled)
966 co = g_pSourcePawn2->StartCompilation();
969 for (unsigned int i=0; i<setcount; i++)
971 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
975 pPlugin->m_type = pset->type_val;
978 for (unsigned int j=0; j<pset->opts_num; j++)
980 const char *key, *val;
981 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
986 if ((err = co->SetOption(key, val)) == SP_ERROR_NONE)
990 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
1000 /* Do the actual compiling */
1003 char fullpath[PLATFORM_MAX_PATH];
1004 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", pPlugin->m_filename);
1006 pPlugin->m_pRuntime = g_pSourcePawn2->LoadPlugin(co, fullpath, &err);
1007 if (pPlugin->m_pRuntime == NULL)
1011 "Unable to load plugin (error %d: %s)",
1013 g_pSourcePawn2->GetErrorString(err));
1014 pPlugin->m_status = Plugin_BadLoad;
1018 if (pPlugin->UpdateInfo())
1020 pPlugin->m_status = Plugin_Created;
1024 UTIL_Format(error, maxlength, "%s", pPlugin->m_errormsg);
1029 LoadRes loadFailure = LoadRes_Failure;
1030 /* Get the status */
1031 if (pPlugin->GetStatus() == Plugin_Created)
1033 /* First native pass - add anything from Core */
1034 g_ShareSys.BindNativesToPlugin(pPlugin, true);
1035 pPlugin->InitIdentity();
1036 APLRes result = pPlugin->Call_AskPluginLoad(error, maxlength);
1039 case APLRes_Success:
1040 /* Autoload any modules */
1041 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
1043 case APLRes_Failure:
1044 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1045 loadFailure = LoadRes_Failure;
1047 case APLRes_SilentFailure:
1048 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1049 loadFailure = LoadRes_SilentFailure;
1050 pPlugin->SetSilentlyFailed(true);
1057 /* Save the time stamp */
1058 time_t t = pPlugin->GetFileTimeStamp();
1059 pPlugin->SetTimeStamp(t);
1066 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : loadFailure;
1069 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
1075 if ((res=_LoadPlugin(&pl, path, true, type, error, maxlength)) == LoadRes_Failure)
1081 if (res == LoadRes_AlreadyLoaded)
1087 if (res == LoadRes_NeverLoad)
1089 if (m_LoadingLocked)
1091 UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect");
1095 UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
1102 /* Run second pass if we need to */
1103 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
1105 if (!RunSecondPass(pl, error, maxlength))
1110 pl->Call_OnAllPluginsLoaded();
1116 void CPluginManager::LoadAutoPlugin(const char *plugin)
1120 char error[255] = "Unknown error";
1122 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
1124 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
1126 pl->GetStatus() == Plugin_BadLoad ? Plugin_BadLoad : Plugin_Failed,
1131 if (res == LoadRes_Successful || res == LoadRes_Failure || res == LoadRes_SilentFailure)
1137 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1139 List<IPluginsListener *>::iterator iter;
1140 IPluginsListener *pListener;
1142 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1144 pListener = (*iter);
1145 pListener->OnPluginCreated(pPlugin);
1148 m_plugins.push_back(pPlugin);
1149 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1152 void CPluginManager::LoadAll_SecondPass()
1154 List<CPlugin *>::iterator iter;
1158 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1161 if (pPlugin->GetStatus() == Plugin_Loaded)
1164 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1166 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1167 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1172 m_AllPluginsLoaded = true;
1175 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1184 IPluginContext *pBase = pPlugin->GetBaseContext();
1185 uint32_t num = pBase->GetPubVarsNum();
1186 sp_pubvar_t *pubvar;
1188 char pathfile[PLATFORM_MAX_PATH];
1190 for (uint32_t i=0; i<num; i++)
1192 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1196 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1198 pl = (_pl *)pubvar->offs;
1199 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1203 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1207 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1208 if (strcmp(pathfile, file) == 0)
1212 if (pl->required == false)
1214 IPluginFunction *pFunc;
1216 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1217 if ((pFunc=pBase->GetFunctionByName(buffer)))
1220 pFunc->Execute(&res);
1221 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1225 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1233 /* Check that we aren't registering the same library twice */
1234 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1236 pPlugin->m_RequiredLibs.push_back(name);
1242 List<CPlugin *>::iterator iter;
1245 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1248 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1258 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1269 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1271 /* Find any extensions this plugin needs */
1280 IPluginContext *pBase = pPlugin->GetBaseContext();
1281 uint32_t num = pBase->GetPubVarsNum();
1282 sp_pubvar_t *pubvar;
1284 char path[PLATFORM_MAX_PATH];
1286 for (uint32_t i=0; i<num; i++)
1288 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1292 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1294 ext = (_ext *)pubvar->offs;
1295 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1299 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1305 /* Attempt to auto-load if necessary */
1308 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1309 g_Extensions.LoadAutoExtension(path);
1314 /* Is this required? */
1317 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1318 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1320 pExt = g_Extensions.FindExtensionByName(name);
1322 /* :TODO: should we bind to unloaded extensions?
1323 * Currently the extension manager will ignore this.
1325 if (!pExt || !pExt->IsRunning(NULL, 0))
1329 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1335 g_Extensions.BindChildPlugin(pExt, pPlugin);
1340 IPluginFunction *pFunc;
1342 UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
1344 if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
1347 pFunc->Execute(&res);
1348 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1352 UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
1365 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1367 /* Second pass for extension requirements */
1368 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1373 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1378 /* Run another binding pass */
1379 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1381 /* Find any unbound natives. Right now, these are not allowed. */
1382 IPluginContext *pContext = pPlugin->GetBaseContext();
1383 uint32_t num = pContext->GetNativesNum();
1384 sp_native_t *native;
1385 for (unsigned int i=0; i<num; i++)
1387 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1391 if (native->status == SP_NATIVE_UNBOUND
1392 && native->name[0] != '@'
1393 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1397 snprintf(error, maxlength, "Native \"%s\" was not found", native->name);
1403 /* Finish by telling all listeners */
1404 List<IPluginsListener *>::iterator iter;
1405 IPluginsListener *pListener;
1406 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1408 pListener = (*iter);
1409 pListener->OnPluginLoaded(pPlugin);
1412 /* Tell this plugin to finish initializing itself */
1413 pPlugin->Call_OnPluginStart();
1415 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1416 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_Natives.size())
1418 List<CPlugin *>::iterator pl_iter;
1420 for (pl_iter = m_plugins.begin();
1421 pl_iter != m_plugins.end();
1424 pOther = (*pl_iter);
1425 if ((pOther->GetStatus() == Plugin_Error
1426 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1427 || pOther->m_FakeNativesMissing)
1429 TryRefreshDependencies(pOther);
1431 else if ((pOther->GetStatus() == Plugin_Running
1432 || pOther->GetStatus() == Plugin_Paused)
1433 && pOther != pPlugin)
1435 List<NativeEntry *>::iterator nv_iter;
1436 for (nv_iter = pPlugin->m_Natives.begin();
1437 nv_iter != pPlugin->m_Natives.end();
1440 g_ShareSys.BindNativeToPlugin(pOther, (*nv_iter));
1446 /* Go through our libraries and tell other plugins they're added */
1447 List<String>::iterator s_iter;
1448 for (s_iter = pPlugin->m_Libraries.begin();
1449 s_iter != pPlugin->m_Libraries.end();
1452 OnLibraryAction((*s_iter).c_str(), true, false);
1455 /* :TODO: optimize? does this even matter? */
1456 pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
1461 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1463 assert(pPlugin->GetBaseContext() != NULL);
1465 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1467 List<String>::iterator lib_iter;
1468 List<String>::iterator req_iter;
1469 List<CPlugin *>::iterator pl_iter;
1471 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1474 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1477 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1479 if ((*req_iter) == (*lib_iter))
1487 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1492 /* Find any unbound natives
1493 * Right now, these are not allowed
1495 IPluginContext *pContext = pPlugin->GetBaseContext();
1496 uint32_t num = pContext->GetNativesNum();
1497 sp_native_t *native;
1498 for (unsigned int i=0; i<num; i++)
1500 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1504 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1506 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1511 if (pPlugin->GetStatus() == Plugin_Error)
1513 /* If we got here, all natives are okay again! */
1514 pPlugin->m_status = Plugin_Running;
1515 if (pPlugin->m_pRuntime->IsPaused())
1517 pPlugin->m_pRuntime->SetPauseState(false);
1518 _SetPauseState(pPlugin, false);
1523 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1525 CPlugin *pPlugin = (CPlugin *)plugin;
1527 /* This prevents removal during insertion or anything else weird */
1528 if (m_plugins.find(pPlugin) == m_plugins.end())
1533 IPluginContext *pContext = plugin->GetBaseContext();
1534 if (pContext != NULL && pContext->IsInExec())
1537 UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
1538 engine->ServerCommand(buffer);
1542 /* Remove us from the lookup table and linked list */
1543 m_plugins.remove(pPlugin);
1544 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1546 /* Go through our libraries and tell other plugins they're gone */
1547 List<String>::iterator s_iter;
1548 for (s_iter = pPlugin->m_Libraries.begin();
1549 s_iter != pPlugin->m_Libraries.end();
1552 OnLibraryAction((*s_iter).c_str(), true, true);
1555 List<IPluginsListener *>::iterator iter;
1556 IPluginsListener *pListener;
1558 if (pPlugin->GetStatus() <= Plugin_Error)
1560 /* Notify listeners of unloading */
1561 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1563 pListener = (*iter);
1564 pListener->OnPluginUnloaded(pPlugin);
1567 pPlugin->Call_OnPluginEnd();
1570 pPlugin->DropEverything();
1572 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1574 /* Notify listeners of destruction */
1575 pListener = (*iter);
1576 pListener->OnPluginDestroyed(pPlugin);
1579 /* Tell the plugin to delete itself */
1585 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1588 IPluginContext *pContext;
1590 pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
1592 if (pContext->GetKey(2, (void **)&pPlugin))
1600 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
1602 return (CPlugin *)FindPluginByContext(ctx);
1605 unsigned int CPluginManager::GetPluginCount()
1607 return m_plugins.size();
1610 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1612 m_listeners.push_back(listener);
1615 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1617 m_listeners.remove(listener);
1620 IPluginIterator *CPluginManager::GetPluginIterator()
1622 if (m_iters.empty())
1624 return new CPluginIterator(&m_plugins);
1626 CPluginIterator *iter = m_iters.front();
1633 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1638 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1640 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1641 size_t alias_len = 0;
1642 size_t local_len = 0;
1644 const char *ptr = alias;
1645 unsigned int alias_explicit_paths = 0;
1646 unsigned int alias_path_end = 0;
1647 while (*ptr != '\0')
1649 if (*ptr == '\\' || *ptr == '/')
1651 alias_explicit_paths++;
1652 alias_path_end = alias_len;
1658 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1660 /* Trailing slash is totally invalid here */
1665 unsigned int local_explicit_paths = 0;
1666 unsigned int local_path_end = 0;
1667 while (*ptr != '\0')
1669 if (*ptr == '\\' || *ptr == '/')
1671 local_explicit_paths++;
1672 local_path_end = local_len;
1678 /* If the alias has more explicit paths than the real path,
1679 * no match will be possible.
1681 if (alias_explicit_paths > local_explicit_paths)
1686 if (alias_explicit_paths)
1688 /* We need to find if the paths match now. For example, these should all match:
1690 * csdm optional/csdm
1691 * csdm/ban optional/crab/csdm/ban
1693 const char *aliasptr = alias;
1694 const char *localptr = localpath;
1698 if (*aliasptr != *localptr)
1700 /* We have to knock one path off */
1701 local_explicit_paths--;
1702 if (alias_explicit_paths > local_explicit_paths)
1704 /* Skip out if we're gonna have an impossible match */
1707 /* Eat up localptr tokens until we get a result */
1708 while (((localptr - localpath) < (int)local_path_end)
1710 && *localptr != '\\')
1714 /* Check if we hit the end of our searchable area.
1715 * This probably isn't possible because of the path
1716 * count check, but it's a good idea anyway.
1718 if ((localptr - localpath) >= (int)local_path_end)
1722 /* Consume the slash token */
1725 /* Reset the alias pointer so we can continue consuming */
1731 * This is safe because if localptr terminates early, aliasptr will too
1735 /* We should never reach the end of the string because of this check. */
1736 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1737 bool localend = (localptr - localpath) > (int)local_path_end;
1738 if (aliasend || localend)
1740 if (aliasend && localend)
1742 /* we matched, and we can break out now */
1746 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1751 /* If we got here, it's safe to compare the next two tokens */
1752 if (*localptr != *aliasptr)
1763 /* If we got here, it's time to compare filenames */
1764 const char *aliasptr = alias;
1765 const char *localptr = localpath;
1767 if (alias_explicit_paths)
1769 aliasptr = &alias[alias_path_end + 1];
1772 if (local_explicit_paths)
1774 localptr = &localpath[local_path_end + 1];
1779 if (*aliasptr == '*')
1781 /* First, see if this is the last character */
1782 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1784 /* If so, there's no need to match anything else */
1787 /* Otherwise, we need to search for an appropriate matching sequence in local.
1788 * Note that we only need to search up to the next asterisk.
1792 const char *local_orig = localptr;
1796 while (*aliasptr != '\0' && *aliasptr != '*')
1798 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1799 if (*aliasptr != *localptr)
1809 /* If we didn't get a match, we need to advance the search stream.
1810 * This will let us skip tokens while still searching for another match.
1812 localptr = ++local_orig;
1813 /* Make sure we don't go out of bounds */
1814 if (*localptr == '\0')
1825 /* If we got a match, move on to the next token */
1828 } else if (*aliasptr == '\0') {
1829 if (*localptr == '\0'
1831 strcmp(localptr, ".smx") == 0)
1837 } else if (*aliasptr != *localptr) {
1847 bool CPluginManager::IsLateLoadTime() const
1849 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1852 void CPluginManager::OnSourceModAllInitialized()
1854 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1857 g_HandleSys.InitAccessDefaults(NULL, &sec);
1859 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1860 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1862 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1863 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1865 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1867 g_ShareSys.AddInterface(NULL, this);
1870 void CPluginManager::OnSourceModShutdown()
1872 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1876 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1877 g_ShareSys.DestroyIdentType(g_PluginIdent);
1878 g_ShareSys.DestroyIdentity(m_MyIdent);
1881 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1883 /* We don't care about the internal object, actually */
1886 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
1888 *pSize = ((CPlugin *)object)->CalcMemUsage();
1892 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1900 sec.pIdentity = m_MyIdent;
1902 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1915 CPlugin *CPluginManager::GetPluginByOrder(int num)
1917 if (num < 1 || num > (int)GetPluginCount())
1925 SourceHook::List<CPlugin *>::iterator iter;
1926 for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
1933 const char *CPluginManager::GetStatusText(PluginStatus st)
1937 case Plugin_Running:
1943 case Plugin_Uncompiled:
1944 return "Uncompiled";
1945 case Plugin_BadLoad:
1955 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
1957 int argcount = command.ArgC();
1960 const char *cmd = command.Arg(2);
1961 if (strcmp(cmd, "list") == 0)
1964 unsigned int id = 1;
1965 int plnum = GetPluginCount();
1969 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1974 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1978 SourceHook::List<CPlugin *>::iterator iter;
1979 SourceHook::List<CPlugin *> m_FailList;
1981 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
1984 assert(pl->GetStatus() != Plugin_Created);
1986 const sm_plugininfo_t *info = pl->GetPublicInfo();
1987 if (pl->GetStatus() != Plugin_Running && !pl->IsSilentlyFailed())
1989 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1991 if (pl->GetStatus() <= Plugin_Error)
1993 /* Plugin has failed to load. */
1994 m_FailList.push_back(pl);
1999 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
2001 if (pl->GetStatus() < Plugin_Created)
2003 if (pl->IsSilentlyFailed())
2004 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " Disabled:");
2005 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2006 if (IS_STR_FILLED(info->version))
2008 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
2010 if (IS_STR_FILLED(info->author))
2012 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
2017 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
2019 g_RootMenu.ConsolePrint("%s", buffer);
2022 if (!m_FailList.empty())
2024 g_RootMenu.ConsolePrint("Load Errors:");
2026 SourceHook::List<CPlugin *>::iterator _iter;
2030 for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
2032 pl = (CPlugin *)*_iter;
2033 g_RootMenu.ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
2039 else if (strcmp(cmd, "load") == 0)
2043 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
2049 const char *filename = command.Arg(3);
2051 char pluginfile[256];
2052 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
2053 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
2055 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
2059 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
2065 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
2069 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
2074 else if (strcmp(cmd, "unload") == 0)
2078 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
2084 const char *arg = command.Arg(3);
2085 int id = strtol(arg, &end, 10);
2089 pl = GetPluginByOrder(id);
2092 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2098 char pluginfile[256];
2099 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2100 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2102 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2104 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2109 char name[PLATFORM_MAX_PATH];
2111 if (pl->GetStatus() < Plugin_Created)
2113 const sm_plugininfo_t *info = pl->GetPublicInfo();
2114 UTIL_Format(name, sizeof(name), (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2118 UTIL_Format(name, sizeof(name), "%s", pl->GetFilename());
2121 if (UnloadPlugin(pl))
2123 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
2127 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
2132 else if (strcmp(cmd, "unload_all") == 0)
2134 g_PluginSys.UnloadAll();
2135 g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
2138 else if (strcmp(cmd, "load_lock") == 0)
2140 if (m_LoadingLocked)
2142 g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
2146 m_LoadingLocked = true;
2147 g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
2151 else if (strcmp(cmd, "load_unlock") == 0)
2153 if (m_LoadingLocked)
2155 m_LoadingLocked = false;
2156 g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
2160 g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
2164 else if (strcmp(cmd, "info") == 0)
2168 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2174 const char *arg = command.Arg(3);
2175 int id = strtol(arg, &end, 10);
2179 pl = GetPluginByOrder(id);
2182 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2188 char pluginfile[256];
2189 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2190 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2192 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2194 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2199 const sm_plugininfo_t *info = pl->GetPublicInfo();
2201 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2202 if (pl->GetStatus() <= Plugin_Error)
2204 if (IS_STR_FILLED(info->name))
2206 if (IS_STR_FILLED(info->description))
2208 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2210 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2213 if (IS_STR_FILLED(info->author))
2215 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2217 if (IS_STR_FILLED(info->version))
2219 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2221 if (IS_STR_FILLED(info->url))
2223 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2225 if (pl->GetStatus() == Plugin_Error)
2227 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2231 if (pl->GetStatus() == Plugin_Running)
2233 g_RootMenu.ConsolePrint(" Status: running");
2237 g_RootMenu.ConsolePrint(" Status: not running");
2240 const char *typestr = "";
2241 switch (pl->GetType())
2243 case PluginType_MapUpdated:
2244 typestr = "Map Change if Updated";
2246 case PluginType_MapOnly:
2247 typestr = "Map Change";
2249 case PluginType_Private:
2250 case PluginType_Global:
2255 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2257 if (pl->m_FileVersion >= 3)
2259 g_RootMenu.ConsolePrint(" Timestamp: %s", pl->m_DateTime);
2264 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2265 if (pl->GetStatus() < Plugin_Created)
2267 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2268 info->name ? info->name : "<none>",
2269 info->version ? info->version : "<none>");
2270 if (IS_STR_FILLED(info->url))
2272 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2279 else if (strcmp(cmd, "refresh") == 0)
2281 g_SourceMod.DoGlobalPluginLoads();
2282 g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
2285 else if (strcmp(cmd, "reload") == 0)
2289 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
2295 const char *arg = command.Arg(3);
2296 int id = strtol(arg, &end, 10);
2300 pl = GetPluginByOrder(id);
2303 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2309 char pluginfile[256];
2310 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2311 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2313 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2315 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2320 char name[PLATFORM_MAX_PATH];
2321 const sm_plugininfo_t *info = pl->GetPublicInfo();
2322 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2324 if (ReloadPlugin(pl))
2326 g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
2330 g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
2337 /* Draw the main menu */
2338 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2339 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2340 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2341 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2342 g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
2343 g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
2344 g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
2345 g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
2346 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2347 g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
2350 bool CPluginManager::ReloadPlugin(CPlugin *pl)
2352 List<CPlugin *>::iterator iter;
2353 char filename[PLATFORM_MAX_PATH];
2359 strcpy(filename, pl->m_filename);
2360 ptype = pl->GetType();
2362 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
2370 if (!UnloadPlugin(pl))
2374 if (!(newpl=LoadPlugin(filename, true, ptype, NULL, 0, &wasloaded)))
2379 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2381 if ((*iter) == (CPlugin *)newpl)
2383 m_plugins.erase(iter);
2389 for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
2392 m_plugins.insert(iter, (CPlugin *)newpl);
2397 void CPluginManager::ReloadOrUnloadPlugins()
2399 /* If we're in a load lock, just skip this whole bit. */
2400 if (m_LoadingLocked)
2405 List<CPlugin *>::iterator iter;
2406 List<CPlugin *> tmp_list = m_plugins;
2410 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2413 if (pl->GetType() == PluginType_MapOnly)
2415 UnloadPlugin((IPlugin *)pl);
2417 else if (pl->GetType() == PluginType_MapUpdated)
2419 t = pl->GetFileTimeStamp();
2420 if (!t || t > pl->GetTimeStamp())
2422 pl->SetTimeStamp(t);
2423 UnloadPlugin((IPlugin *)pl);
2429 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2431 List<IPluginsListener *>::iterator iter;
2432 IPluginsListener *pListener;
2433 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2435 pListener = (*iter);
2436 pListener->OnPluginPauseChange(pl, paused);
2440 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2442 List<CPlugin *>::iterator iter;
2444 IPluginFunction *pFunction;
2446 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2450 if (pPlugin->GetStatus() <= Plugin_Paused)
2452 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2456 pForward->AddFunction(pFunction);
2462 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2464 if (pToken->type != g_PluginIdent)
2469 return (CPlugin *)(pToken->ptr);
2472 void CPluginManager::OnLibraryAction(const char *lib, bool is_a_plugin, bool drop)
2474 List<CPlugin *>::iterator iter;
2491 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2493 for (iter=m_plugins.begin();
2494 iter!=m_plugins.end();
2497 CPlugin *pl = (*iter);
2498 if (pl->GetStatus() != Plugin_Running)
2502 IPluginContext *pContext = pl->GetBaseContext();
2503 IPluginFunction *pf = pContext->GetFunctionByName(name);
2508 uint32_t num_vars = pContext->GetPubVarsNum();
2509 for (uint32_t i=0; i<num_vars; i++)
2511 sp_pubvar_t *pubvar;
2512 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2516 if (is_a_plugin && strncmp(pubvar->name, "__pl_", 5) == 0)
2518 plc = (_pl *)pubvar->offs;
2524 pContext->LocalToString(plc->name, &str);
2525 if (strcmp(str, lib) != 0)
2529 pf->PushString(lib);
2532 else if (!is_a_plugin && strncmp(pubvar->name, "__ext_", 6) == 0)
2534 ext = (_ext *)pubvar->offs;
2540 pContext->LocalToString(ext->name, &str);
2541 if (strcmp(str, lib) != 0)
2545 pf->PushString(lib);
2552 bool CPluginManager::LibraryExists(const char *lib)
2554 List<CPlugin *>::iterator iter;
2556 for (iter=m_plugins.begin();
2557 iter!=m_plugins.end();
2560 CPlugin *pl = (*iter);
2561 if (pl->GetStatus() != Plugin_Running)
2565 List<String>::iterator s_iter;
2566 for (s_iter = pl->m_Libraries.begin();
2567 s_iter != pl->m_Libraries.end();
2570 if ((*s_iter).compare(lib) == 0)
2580 void CPluginManager::AllPluginsLoaded()
2582 List<CPlugin *>::iterator iter;
2585 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2588 pl->Call_OnAllPluginsLoaded();
2592 void CPluginManager::UnloadAll()
2594 List<CPlugin *>::iterator iter;
2595 while ( (iter = m_plugins.begin()) != m_plugins.end() )
2597 UnloadPlugin((*iter));
2601 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
2604 List<CPlugin *>::iterator iter;
2606 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
2617 CPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
2623 id = strtol(arg, &end, 10);
2627 pl = GetPluginByOrder(id);
2635 char pluginfile[256];
2636 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2637 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2639 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2648 void CPluginManager::OnSourceModMaxPlayersChanged(int newvalue)
2650 SyncMaxClients(newvalue);
2653 void CPluginManager::SyncMaxClients(int max_clients)
2655 List<CPlugin *>::iterator iter;
2657 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2659 (*iter)->SyncMaxClients(max_clients);
2663 void CPluginManager::ListPluginsToClient(CPlayer *player, const CCommand &args)
2666 unsigned int id = 0;
2667 int plnum = GetPluginCount();
2668 edict_t *e = player->GetEdict();
2669 unsigned int start = 0;
2673 ClientConsolePrint(e, "[SM] No plugins found.");
2677 if (args.ArgC() > 2)
2679 start = atoi(args.Arg(2));
2683 SourceHook::List<CPlugin *>::iterator iter;
2684 SourceHook::List<CPlugin *> m_FailList;
2686 for (iter = m_plugins.begin();
2687 iter != m_plugins.end();
2692 if (pl->GetStatus() != Plugin_Running)
2697 /* Count valid plugins */
2704 if (id - start > 10)
2710 const sm_plugininfo_t *info = pl->GetPublicInfo();
2711 len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2712 if (IS_STR_FILLED(info->version))
2714 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
2716 if (IS_STR_FILLED(info->author))
2718 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
2722 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
2724 ClientConsolePrint(e, "%s", buffer);
2727 /* See if we can get more plugins */
2728 while (iter != m_plugins.end())
2730 if ((*iter)->GetStatus() == Plugin_Running)
2736 /* Do we actually have more plugins? */
2737 if (iter != m_plugins.end())
2739 ClientConsolePrint(e, "To see more, type \"sm plugins %d\"", id + 1);