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"
41 #include "ExtensionSys.h"
42 #include "sm_srvcmds.h"
43 #include "sm_stringutil.h"
44 #include "ConCmdManager.h"
45 #include "PlayerManager.h"
46 #include "CoreConfig.h"
47 #include "Translator.h"
49 CPluginManager g_PluginSys;
50 HandleType_t g_PluginType = 0;
51 IdentityType_t g_PluginIdent = 0;
53 CPlugin::CPlugin(const char *file)
55 static int MySerial = 0;
57 m_type = PluginType_Private;
58 m_status = Plugin_Uncompiled;
59 m_bSilentlyFailed = false;
60 m_serial = ++MySerial;
62 m_errormsg[256] = '\0';
63 snprintf(m_filename, sizeof(m_filename), "%s", file);
66 m_pProps = sm_trie_create();
67 m_FakeNativesMissing = false;
68 m_LibraryMissing = false;
69 m_bGotAllLoaded = false;
70 m_pPhrases = g_Translator.CreatePhraseCollection();
71 m_MaxClientsVar = NULL;
79 sec.pOwner = g_PluginSys.GetIdentity();
80 sec.pIdentity = sec.pOwner;
82 g_HandleSys.FreeHandle(m_handle, &sec);
83 g_ShareSys.DestroyIdentity(m_ident);
86 if (m_pRuntime != NULL)
94 sm_trie_destroy(m_pProps);
96 for (size_t i=0; i<m_configs.size(); i++)
101 if (m_pPhrases != NULL)
103 m_pPhrases->Destroy();
108 void CPlugin::InitIdentity()
112 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
113 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
114 m_pRuntime->GetDefaultContext()->SetKey(1, m_ident);
115 m_pRuntime->GetDefaultContext()->SetKey(2, (IPlugin *)this);
119 unsigned int CPlugin::CalcMemUsage()
121 unsigned int base_size =
123 + sizeof(IdentityToken_t)
124 + (m_configs.size() * (sizeof(AutoConfig *) + sizeof(AutoConfig)))
125 + sm_trie_mem_usage(m_pProps);
127 for (unsigned int i = 0; i < m_configs.size(); i++)
129 base_size += m_configs[i]->autocfg.size();
130 base_size += m_configs[i]->folder.size();
133 for (List<String>::iterator i = m_Libraries.begin();
134 i != m_Libraries.end();
137 base_size += (*i).size();
140 for (List<String>::iterator i = m_RequiredLibs.begin();
141 i != m_RequiredLibs.end();
144 base_size += (*i).size();
150 Handle_t CPlugin::GetMyHandle()
155 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
157 char fullpath[PLATFORM_MAX_PATH];
158 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
159 FILE *fp = fopen(fullpath, "rb");
161 CPlugin *pPlugin = new CPlugin(file);
167 snprintf(error, maxlength, "Unable to open file");
169 pPlugin->m_status = Plugin_BadLoad;
178 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
180 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
182 if (exists && remove)
184 sm_trie_delete(m_pProps, prop);
190 bool CPlugin::SetProperty(const char *prop, void *ptr)
192 return sm_trie_insert(m_pProps, prop, ptr);
195 IPluginRuntime *CPlugin::GetRuntime()
200 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
202 PluginStatus old_status = m_status;
205 if (old_status == Plugin_Running)
207 /* Tell everyone we're now paused */
208 g_PluginSys._SetPauseState(this, true);
212 va_start(ap, error_fmt);
213 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
216 if (m_pRuntime != NULL)
218 m_pRuntime->SetPauseState(true);
222 bool CPlugin::UpdateInfo()
224 /* Now grab the info */
226 IPluginContext *base = GetBaseContext();
227 int err = base->FindPubvarByName("myinfo", &idx);
229 memset(&m_info, 0, sizeof(m_info));
231 if (err == SP_ERROR_NONE)
233 struct sm_plugininfo_c_t
241 sm_plugininfo_c_t *cinfo;
244 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
245 base->LocalToString(cinfo->name, (char **)&m_info.name);
246 base->LocalToString(cinfo->description, (char **)&m_info.description);
247 base->LocalToString(cinfo->author, (char **)&m_info.author);
248 base->LocalToString(cinfo->url, (char **)&m_info.url);
249 base->LocalToString(cinfo->version, (char **)&m_info.version);
252 m_info.author = m_info.author ? m_info.author : "";
253 m_info.description = m_info.description ? m_info.description : "";
254 m_info.name = m_info.name ? m_info.name : "";
255 m_info.url = m_info.url ? m_info.url : "";
256 m_info.version = m_info.version ? m_info.version : "";
258 if ((err = base->FindPubvarByName("__version", &idx)) == SP_ERROR_NONE)
260 struct __version_info
267 __version_info *info;
269 const char *pDate, *pTime, *pFileVers;
274 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&info);
275 m_FileVersion = info->version;
276 if (m_FileVersion >= 4)
278 base->LocalToString(info->date, (char **)&pDate);
279 base->LocalToString(info->time, (char **)&pTime);
280 UTIL_Format(m_DateTime, sizeof(m_DateTime), "%s %s", pDate, pTime);
282 if (m_FileVersion > 5)
284 base->LocalToString(info->filevers, (char **)&pFileVers);
285 SetErrorState(Plugin_Failed, "Newer SourceMod required (%s or higher)", pFileVers);
294 if ((err = base->FindPubvarByName("MaxClients", &idx)) == SP_ERROR_NONE)
296 base->GetPubvarByIndex(idx, &m_MaxClientsVar);
302 void CPlugin::SyncMaxClients(int max_clients)
304 if (m_MaxClientsVar == NULL)
309 *m_MaxClientsVar->offs = max_clients;
312 void CPlugin::Call_OnPluginStart()
314 if (m_status != Plugin_Loaded)
319 m_status = Plugin_Running;
321 SyncMaxClients(g_Players.MaxClients());
324 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginStart");
331 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
333 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
337 void CPlugin::Call_OnPluginEnd()
339 if (m_status > Plugin_Paused)
345 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginEnd");
351 pFunction->Execute(&result);
354 void CPlugin::Call_OnAllPluginsLoaded()
356 if (m_status > Plugin_Paused)
366 m_bGotAllLoaded = true;
369 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnAllPluginsLoaded");
370 if (pFunction != NULL)
372 pFunction->Execute(&result);
377 if ((pFunction = m_pRuntime->GetFunctionByName("OnMapStart")) != NULL)
379 pFunction->Execute(NULL);
383 if (SM_AreConfigsExecuted())
385 SM_ExecuteForPlugin(GetBaseContext());
389 APLRes CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
391 if (m_status != Plugin_Created)
393 return APLRes_Failure;
396 m_status = Plugin_Loaded;
400 bool haveNewAPL = false;
401 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad2");
407 else if (!(pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad")))
409 return APLRes_Success;
412 pFunction->PushCell(m_handle);
413 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
414 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
415 pFunction->PushCell(maxlength);
416 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
418 return APLRes_Failure;
423 return (APLRes)result;
427 return APLRes_Success;
431 return APLRes_Failure;
435 void *CPlugin::GetPluginStructure()
440 IPluginContext *CPlugin::GetBaseContext()
442 if (m_pRuntime == NULL)
447 return m_pRuntime->GetDefaultContext();
450 sp_context_t *CPlugin::GetContext()
455 const char *CPlugin::GetFilename()
460 PluginType CPlugin::GetType()
465 const sm_plugininfo_t *CPlugin::GetPublicInfo()
467 if (GetStatus() >= Plugin_Created)
474 unsigned int CPlugin::GetSerial()
479 PluginStatus CPlugin::GetStatus()
484 bool CPlugin::IsSilentlyFailed()
486 return m_bSilentlyFailed;
489 bool CPlugin::IsDebugging()
491 if (m_pRuntime == NULL)
499 void CPlugin::SetSilentlyFailed(bool sf)
501 m_bSilentlyFailed = sf;
504 void CPlugin::LibraryActions(bool dropping)
506 List<String>::iterator iter;
507 for (iter = m_Libraries.begin();
508 iter != m_Libraries.end();
511 g_PluginSys.OnLibraryAction((*iter).c_str(), true, dropping);
515 bool CPlugin::SetPauseState(bool paused)
517 if (paused && GetStatus() != Plugin_Running)
520 } else if (!paused && GetStatus() != Plugin_Paused) {
526 LibraryActions(true);
529 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginPauseChange");
533 pFunction->PushCell(paused ? 1 : 0);
534 pFunction->Execute(&result);
539 m_status = Plugin_Paused;
540 m_pRuntime->SetPauseState(true);
542 m_status = Plugin_Running;
543 m_pRuntime->SetPauseState(false);
546 g_PluginSys._SetPauseState(this, paused);
550 LibraryActions(false);
556 IdentityToken_t *CPlugin::GetIdentity()
561 bool CPlugin::IsRunnable()
563 return (m_status <= Plugin_Paused) ? true : false;
566 time_t CPlugin::GetFileTimeStamp()
568 char path[PLATFORM_MAX_PATH];
569 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
570 #ifdef PLATFORM_WINDOWS
572 if (_stat(path, &s) != 0)
573 #elif defined PLATFORM_POSIX
575 if (stat(path, &s) != 0)
586 time_t CPlugin::GetTimeStamp()
591 void CPlugin::SetTimeStamp(time_t t)
596 IPhraseCollection *CPlugin::GetPhrases()
601 void CPlugin::DependencyDropped(CPlugin *pOwner)
608 List<String>::iterator reqlib_iter;
609 List<String>::iterator lib_iter;
610 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
612 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
614 if ((*reqlib_iter) == (*lib_iter))
616 m_LibraryMissing = true;
621 List<NativeEntry *>::iterator iter;
622 NativeEntry *pNative;
625 unsigned int unbound = 0;
627 for (iter = pOwner->m_Natives.begin();
628 iter != pOwner->m_Natives.end();
632 /* Find this native! */
633 if (m_pRuntime->FindNativeByName(pNative->name, &idx) != SP_ERROR_NONE)
638 m_pRuntime->GetNativeByIndex(idx, &native);
640 native->status = SP_NATIVE_UNBOUND;
646 m_FakeNativesMissing = true;
649 /* :IDEA: in the future, add native trapping? */
650 if (m_FakeNativesMissing || m_LibraryMissing)
652 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
656 unsigned int CPlugin::GetConfigCount()
658 return (unsigned int)m_configs.size();
661 AutoConfig *CPlugin::GetConfig(unsigned int i)
663 if (i >= GetConfigCount())
671 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
673 /* Do a check for duplicates to prevent double-execution */
674 for (size_t i = 0; i < m_configs.size(); i++)
676 if (m_configs[i]->autocfg.compare(cfg) == 0
677 && m_configs[i]->folder.compare(folder) == 0
678 && m_configs[i]->create == autoCreate)
684 AutoConfig *c = new AutoConfig;
688 c->create = autoCreate;
690 m_configs.push_back(c);
693 void CPlugin::DropEverything()
696 List<CPlugin *>::iterator iter;
697 List<WeakNative>::iterator wk_iter;
699 /* Tell everyone that depends on us that we're about to drop */
700 for (iter = m_Dependents.begin();
701 iter != m_Dependents.end();
705 pOther->DependencyDropped(this);
708 /* Note: we don't care about things we depend on.
709 * The reason is that extensions have their own cleanup
710 * code for plugins. Although the "right" design would be
711 * to centralize that here, i'm omitting it for now. Thus,
712 * the code below to walk the plugins list will suffice.
715 /* Other plugins could be holding weak references that were
716 * added by us. We need to clean all of those up now.
718 for (iter = g_PluginSys.m_plugins.begin();
719 iter != g_PluginSys.m_plugins.end();
722 (*iter)->DropRefsTo(this);
725 /* Proceed with the rest of the necessities. */
726 CNativeOwner::DropEverything();
729 bool CPlugin::AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func)
733 if ((pEntry = g_ShareSys.AddFakeNative(pFunc, name, func)) == NULL)
738 m_Natives.push_back(pEntry);
747 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
753 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
758 bool CPluginManager::CPluginIterator::MorePlugins()
760 return (current != mylist->end());
763 void CPluginManager::CPluginIterator::NextPlugin()
768 void CPluginManager::CPluginIterator::Release()
770 g_PluginSys.ReleaseIterator(this);
773 CPluginManager::CPluginIterator::~CPluginIterator()
777 void CPluginManager::CPluginIterator::Reset()
779 current = mylist->begin();
786 CPluginManager::CPluginManager()
788 m_LoadLookup = sm_trie_create();
789 m_AllPluginsLoaded = false;
791 m_LoadingLocked = false;
794 CPluginManager::~CPluginManager()
797 * Ignore the fact that there might be plugins in the cache.
798 * This usually means that Core is not being unloaded properly, and everything
799 * will crash anyway. YAY
801 sm_trie_destroy(m_LoadLookup);
803 CStack<CPluginManager::CPluginIterator *>::iterator iter;
804 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
811 void CPluginManager::Shutdown()
813 List<CPlugin *>::iterator iter;
815 while ((iter = m_plugins.begin()) != m_plugins.end())
821 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
823 /* First read in the database of plugin settings */
826 m_AllPluginsLoaded = false;
827 if ((err=textparsers->ParseFile_SMC(config, &m_PluginInfo, &states)) != SMCError_Okay)
829 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
830 const char *err_msg = textparsers->GetSMCErrorString(err);
833 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
837 LoadPluginsFromDir(basedir, NULL);
840 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
842 char base_path[PLATFORM_MAX_PATH];
844 /* Form the current path to start reading from */
845 if (localpath == NULL)
847 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
849 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
852 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
857 g_LibSys.GetPlatformError(error, sizeof(error));
858 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
859 g_Logger.LogError("[SM] Platform returned error: %s", error);
863 while (dir->MoreFiles())
865 if (dir->IsEntryDirectory()
866 && (strcmp(dir->GetEntryName(), ".") != 0)
867 && (strcmp(dir->GetEntryName(), "..") != 0)
868 && (strcmp(dir->GetEntryName(), "disabled") != 0)
869 && (strcmp(dir->GetEntryName(), "optional") != 0))
871 char new_local[PLATFORM_MAX_PATH];
872 if (localpath == NULL)
874 /* If no path yet, don't add a former slash */
875 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
877 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
879 LoadPluginsFromDir(basedir, new_local);
880 } else if (dir->IsEntryFile()) {
881 const char *name = dir->GetEntryName();
882 size_t len = strlen(name);
884 && strcmp(&name[len-4], ".smx") == 0)
886 /* If the filename matches, load the plugin */
887 char plugin[PLATFORM_MAX_PATH];
888 if (localpath == NULL)
890 snprintf(plugin, sizeof(plugin), "%s", name);
892 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
894 LoadAutoPlugin(plugin);
899 g_LibSys.CloseDirectory(dir);
902 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
906 return LoadRes_NeverLoad;
910 bool no_load = false;
911 PluginSettings *pset;
912 unsigned int setcount = m_PluginInfo.GetSettingsNum();
913 for (unsigned int i=0; i<setcount; i++)
915 if ((pset = m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
919 if (pset->blockload_val)
927 * Does this plugin already exist?
930 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
932 /* Check to see if we should try reloading it */
933 if (pPlugin->GetStatus() == Plugin_BadLoad
934 || pPlugin->GetStatus() == Plugin_Error
935 || pPlugin->GetStatus() == Plugin_Failed
938 UnloadPlugin(pPlugin);
946 return LoadRes_AlreadyLoaded;
952 return LoadRes_NeverLoad;
955 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
957 assert(pPlugin != NULL);
959 pPlugin->m_type = PluginType_MapUpdated;
961 ICompilation *co = NULL;
963 if (pPlugin->m_status == Plugin_Uncompiled)
965 co = g_pSourcePawn2->StartCompilation();
968 for (unsigned int i=0; i<setcount; i++)
970 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
974 pPlugin->m_type = pset->type_val;
977 for (unsigned int j=0; j<pset->opts_num; j++)
979 const char *key, *val;
980 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
985 if ((err = co->SetOption(key, val)) == SP_ERROR_NONE)
989 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
999 /* Do the actual compiling */
1002 char fullpath[PLATFORM_MAX_PATH];
1003 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", pPlugin->m_filename);
1005 pPlugin->m_pRuntime = g_pSourcePawn2->LoadPlugin(co, fullpath, &err);
1006 if (pPlugin->m_pRuntime == NULL)
1010 "Unable to load plugin (error %d: %s)",
1012 g_pSourcePawn2->GetErrorString(err));
1013 pPlugin->m_status = Plugin_BadLoad;
1017 if (pPlugin->UpdateInfo())
1019 pPlugin->m_status = Plugin_Created;
1023 UTIL_Format(error, maxlength, "%s", pPlugin->m_errormsg);
1028 LoadRes loadFailure = LoadRes_Failure;
1029 /* Get the status */
1030 if (pPlugin->GetStatus() == Plugin_Created)
1032 /* First native pass - add anything from Core */
1033 g_ShareSys.BindNativesToPlugin(pPlugin, true);
1034 pPlugin->InitIdentity();
1035 APLRes result = pPlugin->Call_AskPluginLoad(error, maxlength);
1038 case APLRes_Success:
1039 /* Autoload any modules */
1040 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
1042 case APLRes_Failure:
1043 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1044 loadFailure = LoadRes_Failure;
1046 case APLRes_SilentFailure:
1047 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1048 loadFailure = LoadRes_SilentFailure;
1049 pPlugin->SetSilentlyFailed(true);
1056 /* Save the time stamp */
1057 time_t t = pPlugin->GetFileTimeStamp();
1058 pPlugin->SetTimeStamp(t);
1065 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : loadFailure;
1068 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
1074 if ((res=_LoadPlugin(&pl, path, true, type, error, maxlength)) == LoadRes_Failure)
1080 if (res == LoadRes_AlreadyLoaded)
1086 if (res == LoadRes_NeverLoad)
1088 if (m_LoadingLocked)
1090 UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect");
1094 UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
1101 /* Run second pass if we need to */
1102 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
1104 if (!RunSecondPass(pl, error, maxlength))
1109 pl->Call_OnAllPluginsLoaded();
1115 void CPluginManager::LoadAutoPlugin(const char *plugin)
1119 char error[255] = "Unknown error";
1121 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
1123 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
1125 pl->GetStatus() == Plugin_BadLoad ? Plugin_BadLoad : Plugin_Failed,
1130 if (res == LoadRes_Successful || res == LoadRes_Failure || res == LoadRes_SilentFailure)
1136 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1138 List<IPluginsListener *>::iterator iter;
1139 IPluginsListener *pListener;
1141 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1143 pListener = (*iter);
1144 pListener->OnPluginCreated(pPlugin);
1147 m_plugins.push_back(pPlugin);
1148 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1151 void CPluginManager::LoadAll_SecondPass()
1153 List<CPlugin *>::iterator iter;
1157 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1160 if (pPlugin->GetStatus() == Plugin_Loaded)
1163 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1165 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1166 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1171 m_AllPluginsLoaded = true;
1174 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1183 IPluginContext *pBase = pPlugin->GetBaseContext();
1184 uint32_t num = pBase->GetPubVarsNum();
1185 sp_pubvar_t *pubvar;
1187 char pathfile[PLATFORM_MAX_PATH];
1189 for (uint32_t i=0; i<num; i++)
1191 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1195 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1197 pl = (_pl *)pubvar->offs;
1198 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1202 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1206 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1207 if (strcmp(pathfile, file) == 0)
1211 if (pl->required == false)
1213 IPluginFunction *pFunc;
1215 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1216 if ((pFunc=pBase->GetFunctionByName(buffer)))
1219 pFunc->Execute(&res);
1220 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1224 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1232 /* Check that we aren't registering the same library twice */
1233 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1235 pPlugin->m_RequiredLibs.push_back(name);
1241 List<CPlugin *>::iterator iter;
1244 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1247 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1257 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1268 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1270 /* Find any extensions this plugin needs */
1279 IPluginContext *pBase = pPlugin->GetBaseContext();
1280 uint32_t num = pBase->GetPubVarsNum();
1281 sp_pubvar_t *pubvar;
1283 char path[PLATFORM_MAX_PATH];
1285 for (uint32_t i=0; i<num; i++)
1287 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1291 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1293 ext = (_ext *)pubvar->offs;
1294 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1298 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1304 /* Attempt to auto-load if necessary */
1307 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1308 g_Extensions.LoadAutoExtension(path);
1313 /* Is this required? */
1316 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1317 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1319 pExt = g_Extensions.FindExtensionByName(name);
1321 /* :TODO: should we bind to unloaded extensions?
1322 * Currently the extension manager will ignore this.
1324 if (!pExt || !pExt->IsRunning(NULL, 0))
1328 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1334 g_Extensions.BindChildPlugin(pExt, pPlugin);
1339 IPluginFunction *pFunc;
1341 UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
1343 if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
1346 pFunc->Execute(&res);
1347 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1351 UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
1364 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1366 /* Second pass for extension requirements */
1367 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1372 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1377 /* Run another binding pass */
1378 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1380 /* Find any unbound natives. Right now, these are not allowed. */
1381 IPluginContext *pContext = pPlugin->GetBaseContext();
1382 uint32_t num = pContext->GetNativesNum();
1383 sp_native_t *native;
1384 for (unsigned int i=0; i<num; i++)
1386 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1390 if (native->status == SP_NATIVE_UNBOUND
1391 && native->name[0] != '@'
1392 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1396 snprintf(error, maxlength, "Native \"%s\" was not found", native->name);
1402 /* Finish by telling all listeners */
1403 List<IPluginsListener *>::iterator iter;
1404 IPluginsListener *pListener;
1405 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1407 pListener = (*iter);
1408 pListener->OnPluginLoaded(pPlugin);
1411 /* Tell this plugin to finish initializing itself */
1412 pPlugin->Call_OnPluginStart();
1414 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1415 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_Natives.size())
1417 List<CPlugin *>::iterator pl_iter;
1419 for (pl_iter = m_plugins.begin();
1420 pl_iter != m_plugins.end();
1423 pOther = (*pl_iter);
1424 if ((pOther->GetStatus() == Plugin_Error
1425 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1426 || pOther->m_FakeNativesMissing)
1428 TryRefreshDependencies(pOther);
1430 else if ((pOther->GetStatus() == Plugin_Running
1431 || pOther->GetStatus() == Plugin_Paused)
1432 && pOther != pPlugin)
1434 List<NativeEntry *>::iterator nv_iter;
1435 for (nv_iter = pPlugin->m_Natives.begin();
1436 nv_iter != pPlugin->m_Natives.end();
1439 g_ShareSys.BindNativeToPlugin(pOther, (*nv_iter));
1445 /* Go through our libraries and tell other plugins they're added */
1446 List<String>::iterator s_iter;
1447 for (s_iter = pPlugin->m_Libraries.begin();
1448 s_iter != pPlugin->m_Libraries.end();
1451 OnLibraryAction((*s_iter).c_str(), true, false);
1454 /* :TODO: optimize? does this even matter? */
1455 pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
1460 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1462 assert(pPlugin->GetBaseContext() != NULL);
1464 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1466 List<String>::iterator lib_iter;
1467 List<String>::iterator req_iter;
1468 List<CPlugin *>::iterator pl_iter;
1470 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1473 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1476 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1478 if ((*req_iter) == (*lib_iter))
1486 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1491 /* Find any unbound natives
1492 * Right now, these are not allowed
1494 IPluginContext *pContext = pPlugin->GetBaseContext();
1495 uint32_t num = pContext->GetNativesNum();
1496 sp_native_t *native;
1497 for (unsigned int i=0; i<num; i++)
1499 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1503 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1505 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1510 if (pPlugin->GetStatus() == Plugin_Error)
1512 /* If we got here, all natives are okay again! */
1513 pPlugin->m_status = Plugin_Running;
1514 if (pPlugin->m_pRuntime->IsPaused())
1516 pPlugin->m_pRuntime->SetPauseState(false);
1517 _SetPauseState(pPlugin, false);
1522 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1524 CPlugin *pPlugin = (CPlugin *)plugin;
1526 /* This prevents removal during insertion or anything else weird */
1527 if (m_plugins.find(pPlugin) == m_plugins.end())
1532 IPluginContext *pContext = plugin->GetBaseContext();
1533 if (pContext != NULL && pContext->IsInExec())
1536 UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
1537 engine->ServerCommand(buffer);
1541 /* Remove us from the lookup table and linked list */
1542 m_plugins.remove(pPlugin);
1543 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1545 /* Go through our libraries and tell other plugins they're gone */
1546 List<String>::iterator s_iter;
1547 for (s_iter = pPlugin->m_Libraries.begin();
1548 s_iter != pPlugin->m_Libraries.end();
1551 OnLibraryAction((*s_iter).c_str(), true, true);
1554 List<IPluginsListener *>::iterator iter;
1555 IPluginsListener *pListener;
1557 if (pPlugin->GetStatus() <= Plugin_Error)
1559 /* Notify listeners of unloading */
1560 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1562 pListener = (*iter);
1563 pListener->OnPluginUnloaded(pPlugin);
1566 pPlugin->Call_OnPluginEnd();
1569 pPlugin->DropEverything();
1571 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1573 /* Notify listeners of destruction */
1574 pListener = (*iter);
1575 pListener->OnPluginDestroyed(pPlugin);
1578 /* Tell the plugin to delete itself */
1584 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1587 IPluginContext *pContext;
1589 pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
1591 if (pContext->GetKey(2, (void **)&pPlugin))
1599 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
1601 return (CPlugin *)FindPluginByContext(ctx);
1604 unsigned int CPluginManager::GetPluginCount()
1606 return m_plugins.size();
1609 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1611 m_listeners.push_back(listener);
1614 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1616 m_listeners.remove(listener);
1619 IPluginIterator *CPluginManager::GetPluginIterator()
1621 if (m_iters.empty())
1623 return new CPluginIterator(&m_plugins);
1625 CPluginIterator *iter = m_iters.front();
1632 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1637 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1639 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1640 size_t alias_len = 0;
1641 size_t local_len = 0;
1643 const char *ptr = alias;
1644 unsigned int alias_explicit_paths = 0;
1645 unsigned int alias_path_end = 0;
1646 while (*ptr != '\0')
1648 if (*ptr == '\\' || *ptr == '/')
1650 alias_explicit_paths++;
1651 alias_path_end = alias_len;
1657 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1659 /* Trailing slash is totally invalid here */
1664 unsigned int local_explicit_paths = 0;
1665 unsigned int local_path_end = 0;
1666 while (*ptr != '\0')
1668 if (*ptr == '\\' || *ptr == '/')
1670 local_explicit_paths++;
1671 local_path_end = local_len;
1677 /* If the alias has more explicit paths than the real path,
1678 * no match will be possible.
1680 if (alias_explicit_paths > local_explicit_paths)
1685 if (alias_explicit_paths)
1687 /* We need to find if the paths match now. For example, these should all match:
1689 * csdm optional/csdm
1690 * csdm/ban optional/crab/csdm/ban
1692 const char *aliasptr = alias;
1693 const char *localptr = localpath;
1697 if (*aliasptr != *localptr)
1699 /* We have to knock one path off */
1700 local_explicit_paths--;
1701 if (alias_explicit_paths > local_explicit_paths)
1703 /* Skip out if we're gonna have an impossible match */
1706 /* Eat up localptr tokens until we get a result */
1707 while (((localptr - localpath) < (int)local_path_end)
1709 && *localptr != '\\')
1713 /* Check if we hit the end of our searchable area.
1714 * This probably isn't possible because of the path
1715 * count check, but it's a good idea anyway.
1717 if ((localptr - localpath) >= (int)local_path_end)
1721 /* Consume the slash token */
1724 /* Reset the alias pointer so we can continue consuming */
1730 * This is safe because if localptr terminates early, aliasptr will too
1734 /* We should never reach the end of the string because of this check. */
1735 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1736 bool localend = (localptr - localpath) > (int)local_path_end;
1737 if (aliasend || localend)
1739 if (aliasend && localend)
1741 /* we matched, and we can break out now */
1745 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1750 /* If we got here, it's safe to compare the next two tokens */
1751 if (*localptr != *aliasptr)
1762 /* If we got here, it's time to compare filenames */
1763 const char *aliasptr = alias;
1764 const char *localptr = localpath;
1766 if (alias_explicit_paths)
1768 aliasptr = &alias[alias_path_end + 1];
1771 if (local_explicit_paths)
1773 localptr = &localpath[local_path_end + 1];
1778 if (*aliasptr == '*')
1780 /* First, see if this is the last character */
1781 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1783 /* If so, there's no need to match anything else */
1786 /* Otherwise, we need to search for an appropriate matching sequence in local.
1787 * Note that we only need to search up to the next asterisk.
1791 const char *local_orig = localptr;
1795 while (*aliasptr != '\0' && *aliasptr != '*')
1797 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1798 if (*aliasptr != *localptr)
1808 /* If we didn't get a match, we need to advance the search stream.
1809 * This will let us skip tokens while still searching for another match.
1811 localptr = ++local_orig;
1812 /* Make sure we don't go out of bounds */
1813 if (*localptr == '\0')
1824 /* If we got a match, move on to the next token */
1827 } else if (*aliasptr == '\0') {
1828 if (*localptr == '\0'
1830 strcmp(localptr, ".smx") == 0)
1836 } else if (*aliasptr != *localptr) {
1846 bool CPluginManager::IsLateLoadTime() const
1848 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1851 void CPluginManager::OnSourceModAllInitialized()
1853 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1856 g_HandleSys.InitAccessDefaults(NULL, &sec);
1858 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1859 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1861 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1862 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1864 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1866 g_ShareSys.AddInterface(NULL, this);
1869 void CPluginManager::OnSourceModShutdown()
1871 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1875 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1876 g_ShareSys.DestroyIdentType(g_PluginIdent);
1877 g_ShareSys.DestroyIdentity(m_MyIdent);
1880 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1882 /* We don't care about the internal object, actually */
1885 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
1887 *pSize = ((CPlugin *)object)->CalcMemUsage();
1891 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1899 sec.pIdentity = m_MyIdent;
1901 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1914 CPlugin *CPluginManager::GetPluginByOrder(int num)
1916 if (num < 1 || num > (int)GetPluginCount())
1924 SourceHook::List<CPlugin *>::iterator iter;
1925 for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
1932 const char *CPluginManager::GetStatusText(PluginStatus st)
1936 case Plugin_Running:
1942 case Plugin_Uncompiled:
1943 return "Uncompiled";
1944 case Plugin_BadLoad:
1954 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
1956 int argcount = command.ArgC();
1959 const char *cmd = command.Arg(2);
1960 if (strcmp(cmd, "list") == 0)
1963 unsigned int id = 1;
1964 int plnum = GetPluginCount();
1968 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1973 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1977 SourceHook::List<CPlugin *>::iterator iter;
1978 SourceHook::List<CPlugin *> m_FailList;
1980 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
1983 assert(pl->GetStatus() != Plugin_Created);
1985 const sm_plugininfo_t *info = pl->GetPublicInfo();
1986 if (pl->GetStatus() != Plugin_Running && !pl->IsSilentlyFailed())
1988 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1990 if (pl->GetStatus() <= Plugin_Error)
1992 /* Plugin has failed to load. */
1993 m_FailList.push_back(pl);
1998 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
2000 if (pl->GetStatus() < Plugin_Created)
2002 if (pl->IsSilentlyFailed())
2003 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " Disabled:");
2004 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2005 if (IS_STR_FILLED(info->version))
2007 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
2009 if (IS_STR_FILLED(info->author))
2011 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
2016 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
2018 g_RootMenu.ConsolePrint("%s", buffer);
2021 if (!m_FailList.empty())
2023 g_RootMenu.ConsolePrint("Load Errors:");
2025 SourceHook::List<CPlugin *>::iterator _iter;
2029 for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
2031 pl = (CPlugin *)*_iter;
2032 g_RootMenu.ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
2038 else if (strcmp(cmd, "load") == 0)
2042 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
2048 const char *filename = command.Arg(3);
2050 char pluginfile[256];
2051 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
2052 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
2054 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
2058 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
2064 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
2068 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
2073 else if (strcmp(cmd, "unload") == 0)
2077 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
2083 const char *arg = command.Arg(3);
2084 int id = strtol(arg, &end, 10);
2088 pl = GetPluginByOrder(id);
2091 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2097 char pluginfile[256];
2098 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2099 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2101 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2103 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2108 char name[PLATFORM_MAX_PATH];
2110 if (pl->GetStatus() < Plugin_Created)
2112 const sm_plugininfo_t *info = pl->GetPublicInfo();
2113 UTIL_Format(name, sizeof(name), (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2117 UTIL_Format(name, sizeof(name), "%s", pl->GetFilename());
2120 if (UnloadPlugin(pl))
2122 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
2126 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
2131 else if (strcmp(cmd, "unload_all") == 0)
2133 g_PluginSys.UnloadAll();
2134 g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
2137 else if (strcmp(cmd, "load_lock") == 0)
2139 if (m_LoadingLocked)
2141 g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
2145 m_LoadingLocked = true;
2146 g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
2150 else if (strcmp(cmd, "load_unlock") == 0)
2152 if (m_LoadingLocked)
2154 m_LoadingLocked = false;
2155 g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
2159 g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
2163 else if (strcmp(cmd, "info") == 0)
2167 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2173 const char *arg = command.Arg(3);
2174 int id = strtol(arg, &end, 10);
2178 pl = GetPluginByOrder(id);
2181 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2187 char pluginfile[256];
2188 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2189 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2191 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2193 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2198 const sm_plugininfo_t *info = pl->GetPublicInfo();
2200 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2201 if (pl->GetStatus() <= Plugin_Error)
2203 if (IS_STR_FILLED(info->name))
2205 if (IS_STR_FILLED(info->description))
2207 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2209 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2212 if (IS_STR_FILLED(info->author))
2214 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2216 if (IS_STR_FILLED(info->version))
2218 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2220 if (IS_STR_FILLED(info->url))
2222 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2224 if (pl->GetStatus() == Plugin_Error)
2226 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2230 if (pl->GetStatus() == Plugin_Running)
2232 g_RootMenu.ConsolePrint(" Status: running");
2236 g_RootMenu.ConsolePrint(" Status: not running");
2239 const char *typestr = "";
2240 switch (pl->GetType())
2242 case PluginType_MapUpdated:
2243 typestr = "Map Change if Updated";
2245 case PluginType_MapOnly:
2246 typestr = "Map Change";
2248 case PluginType_Private:
2249 case PluginType_Global:
2254 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2256 if (pl->m_FileVersion >= 3)
2258 g_RootMenu.ConsolePrint(" Timestamp: %s", pl->m_DateTime);
2263 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2264 if (pl->GetStatus() < Plugin_Created)
2266 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2267 info->name ? info->name : "<none>",
2268 info->version ? info->version : "<none>");
2269 if (IS_STR_FILLED(info->url))
2271 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2278 else if (strcmp(cmd, "refresh") == 0)
2280 g_SourceMod.DoGlobalPluginLoads();
2281 g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
2284 else if (strcmp(cmd, "reload") == 0)
2288 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
2294 const char *arg = command.Arg(3);
2295 int id = strtol(arg, &end, 10);
2299 pl = GetPluginByOrder(id);
2302 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2308 char pluginfile[256];
2309 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2310 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2312 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2314 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2319 char name[PLATFORM_MAX_PATH];
2320 const sm_plugininfo_t *info = pl->GetPublicInfo();
2321 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2323 if (ReloadPlugin(pl))
2325 g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
2329 g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
2336 /* Draw the main menu */
2337 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2338 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2339 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2340 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2341 g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
2342 g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
2343 g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
2344 g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
2345 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2346 g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
2349 bool CPluginManager::ReloadPlugin(CPlugin *pl)
2351 List<CPlugin *>::iterator iter;
2352 char filename[PLATFORM_MAX_PATH];
2358 strcpy(filename, pl->m_filename);
2359 ptype = pl->GetType();
2361 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
2369 if (!UnloadPlugin(pl))
2373 if (!(newpl=LoadPlugin(filename, true, ptype, NULL, 0, &wasloaded)))
2378 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2380 if ((*iter) == (CPlugin *)newpl)
2382 m_plugins.erase(iter);
2388 for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
2391 m_plugins.insert(iter, (CPlugin *)newpl);
2396 void CPluginManager::ReloadOrUnloadPlugins()
2398 /* If we're in a load lock, just skip this whole bit. */
2399 if (m_LoadingLocked)
2404 List<CPlugin *>::iterator iter;
2405 List<CPlugin *> tmp_list = m_plugins;
2409 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2412 if (pl->GetType() == PluginType_MapOnly)
2414 UnloadPlugin((IPlugin *)pl);
2416 else if (pl->GetType() == PluginType_MapUpdated)
2418 t = pl->GetFileTimeStamp();
2419 if (!t || t > pl->GetTimeStamp())
2421 pl->SetTimeStamp(t);
2422 UnloadPlugin((IPlugin *)pl);
2428 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2430 List<IPluginsListener *>::iterator iter;
2431 IPluginsListener *pListener;
2432 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2434 pListener = (*iter);
2435 pListener->OnPluginPauseChange(pl, paused);
2439 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2441 List<CPlugin *>::iterator iter;
2443 IPluginFunction *pFunction;
2445 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2449 if (pPlugin->GetStatus() <= Plugin_Paused)
2451 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2455 pForward->AddFunction(pFunction);
2461 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2463 if (pToken->type != g_PluginIdent)
2468 return (CPlugin *)(pToken->ptr);
2471 void CPluginManager::OnLibraryAction(const char *lib, bool is_a_plugin, bool drop)
2473 List<CPlugin *>::iterator iter;
2490 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2492 for (iter=m_plugins.begin();
2493 iter!=m_plugins.end();
2496 CPlugin *pl = (*iter);
2497 if (pl->GetStatus() != Plugin_Running)
2501 IPluginContext *pContext = pl->GetBaseContext();
2502 IPluginFunction *pf = pContext->GetFunctionByName(name);
2507 uint32_t num_vars = pContext->GetPubVarsNum();
2508 for (uint32_t i=0; i<num_vars; i++)
2510 sp_pubvar_t *pubvar;
2511 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2515 if (is_a_plugin && strncmp(pubvar->name, "__pl_", 5) == 0)
2517 plc = (_pl *)pubvar->offs;
2523 pContext->LocalToString(plc->name, &str);
2524 if (strcmp(str, lib) != 0)
2528 pf->PushString(lib);
2531 else if (!is_a_plugin && strncmp(pubvar->name, "__ext_", 6) == 0)
2533 ext = (_ext *)pubvar->offs;
2539 pContext->LocalToString(ext->name, &str);
2540 if (strcmp(str, lib) != 0)
2544 pf->PushString(lib);
2551 bool CPluginManager::LibraryExists(const char *lib)
2553 List<CPlugin *>::iterator iter;
2555 for (iter=m_plugins.begin();
2556 iter!=m_plugins.end();
2559 CPlugin *pl = (*iter);
2560 if (pl->GetStatus() != Plugin_Running)
2564 List<String>::iterator s_iter;
2565 for (s_iter = pl->m_Libraries.begin();
2566 s_iter != pl->m_Libraries.end();
2569 if ((*s_iter).compare(lib) == 0)
2579 void CPluginManager::AllPluginsLoaded()
2581 List<CPlugin *>::iterator iter;
2584 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2587 pl->Call_OnAllPluginsLoaded();
2591 void CPluginManager::UnloadAll()
2593 List<CPlugin *>::iterator iter;
2594 while ( (iter = m_plugins.begin()) != m_plugins.end() )
2596 UnloadPlugin((*iter));
2600 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
2603 List<CPlugin *>::iterator iter;
2605 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
2616 CPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
2622 id = strtol(arg, &end, 10);
2626 pl = GetPluginByOrder(id);
2634 char pluginfile[256];
2635 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2636 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2638 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2647 void CPluginManager::OnSourceModMaxPlayersChanged(int newvalue)
2649 SyncMaxClients(newvalue);
2652 void CPluginManager::SyncMaxClients(int max_clients)
2654 List<CPlugin *>::iterator iter;
2656 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2658 (*iter)->SyncMaxClients(max_clients);
2662 void CPluginManager::ListPluginsToClient(CPlayer *player, const CCommand &args)
2665 unsigned int id = 0;
2666 int plnum = GetPluginCount();
2667 edict_t *e = player->GetEdict();
2668 unsigned int start = 0;
2672 ClientConsolePrint(e, "[SM] No plugins found.");
2676 if (args.ArgC() > 2)
2678 start = atoi(args.Arg(2));
2682 SourceHook::List<CPlugin *>::iterator iter;
2683 SourceHook::List<CPlugin *> m_FailList;
2685 for (iter = m_plugins.begin();
2686 iter != m_plugins.end();
2691 if (pl->GetStatus() != Plugin_Running)
2696 /* Count valid plugins */
2703 if (id - start > 10)
2709 const sm_plugininfo_t *info = pl->GetPublicInfo();
2710 len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2711 if (IS_STR_FILLED(info->version))
2713 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
2715 if (IS_STR_FILLED(info->author))
2717 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
2721 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
2723 ClientConsolePrint(e, "%s", buffer);
2726 /* See if we can get more plugins */
2727 while (iter != m_plugins.end())
2729 if ((*iter)->GetStatus() == Plugin_Running)
2735 /* Do we actually have more plugins? */
2736 if (iter != m_plugins.end())
2738 ClientConsolePrint(e, "To see more, type \"sm plugins %d\"", id + 1);