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 "logic_bridge.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[sizeof(m_errormsg) - 1] = '\0';
63 UTIL_Format(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 = 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 UTIL_Format(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 UTIL_FormatArgs(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);
375 if (g_SourceMod.IsMapRunning())
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;
793 m_bBlockBadPlugins = true;
796 CPluginManager::~CPluginManager()
799 * Ignore the fact that there might be plugins in the cache.
800 * This usually means that Core is not being unloaded properly, and everything
801 * will crash anyway. YAY
803 sm_trie_destroy(m_LoadLookup);
805 CStack<CPluginManager::CPluginIterator *>::iterator iter;
806 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
813 void CPluginManager::Shutdown()
815 List<CPlugin *>::iterator iter;
817 while ((iter = m_plugins.begin()) != m_plugins.end())
823 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
825 /* First read in the database of plugin settings */
828 m_AllPluginsLoaded = false;
829 if ((err=textparsers->ParseFile_SMC(config, &m_PluginInfo, &states)) != SMCError_Okay)
831 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
832 const char *err_msg = textparsers->GetSMCErrorString(err);
835 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
839 LoadPluginsFromDir(basedir, NULL);
842 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
844 char base_path[PLATFORM_MAX_PATH];
846 /* Form the current path to start reading from */
847 if (localpath == NULL)
849 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
851 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
854 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
859 g_LibSys.GetPlatformError(error, sizeof(error));
860 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
861 g_Logger.LogError("[SM] Platform returned error: %s", error);
865 while (dir->MoreFiles())
867 if (dir->IsEntryDirectory()
868 && (strcmp(dir->GetEntryName(), ".") != 0)
869 && (strcmp(dir->GetEntryName(), "..") != 0)
870 && (strcmp(dir->GetEntryName(), "disabled") != 0)
871 && (strcmp(dir->GetEntryName(), "optional") != 0))
873 char new_local[PLATFORM_MAX_PATH];
874 if (localpath == NULL)
876 /* If no path yet, don't add a former slash */
877 UTIL_Format(new_local, sizeof(new_local), "%s", dir->GetEntryName());
879 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
881 LoadPluginsFromDir(basedir, new_local);
882 } else if (dir->IsEntryFile()) {
883 const char *name = dir->GetEntryName();
884 size_t len = strlen(name);
886 && strcmp(&name[len-4], ".smx") == 0)
888 /* If the filename matches, load the plugin */
889 char plugin[PLATFORM_MAX_PATH];
890 if (localpath == NULL)
892 UTIL_Format(plugin, sizeof(plugin), "%s", name);
894 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
896 LoadAutoPlugin(plugin);
901 g_LibSys.CloseDirectory(dir);
904 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
908 return LoadRes_NeverLoad;
912 bool no_load = false;
913 PluginSettings *pset;
914 unsigned int setcount = m_PluginInfo.GetSettingsNum();
915 for (unsigned int i=0; i<setcount; i++)
917 if ((pset = m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
921 if (pset->blockload_val)
929 * Does this plugin already exist?
932 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
934 /* Check to see if we should try reloading it */
935 if (pPlugin->GetStatus() == Plugin_BadLoad
936 || pPlugin->GetStatus() == Plugin_Error
937 || pPlugin->GetStatus() == Plugin_Failed
940 UnloadPlugin(pPlugin);
948 return LoadRes_AlreadyLoaded;
954 return LoadRes_NeverLoad;
957 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
959 assert(pPlugin != NULL);
961 pPlugin->m_type = PluginType_MapUpdated;
963 ICompilation *co = NULL;
965 if (pPlugin->m_status == Plugin_Uncompiled)
967 co = g_pSourcePawn2->StartCompilation();
970 for (unsigned int i=0; i<setcount; i++)
972 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
976 pPlugin->m_type = pset->type_val;
979 for (unsigned int j=0; j<pset->opts_num; j++)
981 const char *key, *val;
982 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
987 if ((err = co->SetOption(key, val)) == SP_ERROR_NONE)
991 UTIL_Format(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
1001 /* Do the actual compiling */
1004 char fullpath[PLATFORM_MAX_PATH];
1005 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", pPlugin->m_filename);
1007 pPlugin->m_pRuntime = g_pSourcePawn2->LoadPlugin(co, fullpath, &err);
1008 if (pPlugin->m_pRuntime == NULL)
1014 "Unable to load plugin (error %d: %s)",
1016 g_pSourcePawn2->GetErrorString(err));
1018 pPlugin->m_status = Plugin_BadLoad;
1022 if (pPlugin->UpdateInfo())
1024 pPlugin->m_status = Plugin_Created;
1030 UTIL_Format(error, maxlength, "%s", pPlugin->m_errormsg);
1036 if (pPlugin->GetStatus() == Plugin_Created)
1038 unsigned char *pCodeHash = pPlugin->m_pRuntime->GetCodeHash();
1040 char codeHashBuf[40];
1041 UTIL_Format(codeHashBuf, 40, "plugin_");
1042 for (int i = 0; i < 16; i++)
1043 UTIL_Format(codeHashBuf + 7 + (i * 2), 3, "%02x", pCodeHash[i]);
1045 const char *bulletinUrl = g_pGameConf->GetKeyValue(codeHashBuf);
1046 if (bulletinUrl != NULL)
1048 if (m_bBlockBadPlugins)
1052 if (bulletinUrl[0] != '\0')
1054 UTIL_Format(error, maxlength, "Known malware detected and blocked. See %s for more info", bulletinUrl);
1056 UTIL_Format(error, maxlength, "Possible malware or illegal plugin detected and blocked");
1059 pPlugin->m_status = Plugin_BadLoad;
1061 if (bulletinUrl[0] != '\0')
1063 g_Logger.LogMessage("%s: Known malware detected. See %s for more info, blocking disabled in core.cfg", pPlugin->GetFilename(), bulletinUrl);
1065 g_Logger.LogMessage("%s: Possible malware or illegal plugin detected, blocking disabled in core.cfg", pPlugin->GetFilename());
1071 LoadRes loadFailure = LoadRes_Failure;
1072 /* Get the status */
1073 if (pPlugin->GetStatus() == Plugin_Created)
1075 /* First native pass - add anything from Core */
1076 g_ShareSys.BindNativesToPlugin(pPlugin, true);
1077 pPlugin->InitIdentity();
1078 APLRes result = pPlugin->Call_AskPluginLoad(error, maxlength);
1081 case APLRes_Success:
1082 /* Autoload any modules */
1083 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
1085 case APLRes_Failure:
1086 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1087 loadFailure = LoadRes_Failure;
1089 case APLRes_SilentFailure:
1090 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1091 loadFailure = LoadRes_SilentFailure;
1092 pPlugin->SetSilentlyFailed(true);
1099 /* Save the time stamp */
1100 time_t t = pPlugin->GetFileTimeStamp();
1101 pPlugin->SetTimeStamp(t);
1108 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : loadFailure;
1111 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
1117 if ((res=_LoadPlugin(&pl, path, true, type, error, maxlength)) == LoadRes_Failure)
1123 if (res == LoadRes_AlreadyLoaded)
1129 if (res == LoadRes_NeverLoad)
1133 if (m_LoadingLocked)
1135 UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect");
1139 UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
1147 /* Run second pass if we need to */
1148 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
1150 if (!RunSecondPass(pl, error, maxlength))
1155 pl->Call_OnAllPluginsLoaded();
1161 void CPluginManager::LoadAutoPlugin(const char *plugin)
1165 char error[255] = "Unknown error";
1167 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
1169 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s.", plugin, error);
1171 pl->GetStatus() <= Plugin_Created ? Plugin_BadLoad : pl->GetStatus(),
1176 if (res == LoadRes_Successful || res == LoadRes_Failure || res == LoadRes_SilentFailure)
1182 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1184 List<IPluginsListener *>::iterator iter;
1185 IPluginsListener *pListener;
1187 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1189 pListener = (*iter);
1190 pListener->OnPluginCreated(pPlugin);
1193 m_plugins.push_back(pPlugin);
1194 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1197 void CPluginManager::LoadAll_SecondPass()
1199 List<CPlugin *>::iterator iter;
1203 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1206 if (pPlugin->GetStatus() == Plugin_Loaded)
1209 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1211 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1212 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1217 m_AllPluginsLoaded = true;
1220 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1229 IPluginContext *pBase = pPlugin->GetBaseContext();
1230 uint32_t num = pBase->GetPubVarsNum();
1231 sp_pubvar_t *pubvar;
1233 char pathfile[PLATFORM_MAX_PATH];
1235 for (uint32_t i=0; i<num; i++)
1237 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1241 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1243 pl = (_pl *)pubvar->offs;
1244 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1248 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1252 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1253 if (strcmp(pathfile, file) == 0)
1257 if (pl->required == false)
1259 IPluginFunction *pFunc;
1261 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1262 if ((pFunc=pBase->GetFunctionByName(buffer)))
1265 pFunc->Execute(&res);
1266 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1270 UTIL_Format(error, maxlength, "Fatal error during initializing plugin load");
1278 /* Check that we aren't registering the same library twice */
1279 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1281 pPlugin->m_RequiredLibs.push_back(name);
1287 List<CPlugin *>::iterator iter;
1290 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1293 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1303 UTIL_Format(error, maxlength, "Could not find required plugin \"%s\"", name);
1314 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1316 /* Find any extensions this plugin needs */
1325 IPluginContext *pBase = pPlugin->GetBaseContext();
1326 uint32_t num = pBase->GetPubVarsNum();
1327 sp_pubvar_t *pubvar;
1329 char path[PLATFORM_MAX_PATH];
1331 for (uint32_t i=0; i<num; i++)
1333 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1337 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1339 ext = (_ext *)pubvar->offs;
1340 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1344 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1350 /* Attempt to auto-load if necessary */
1353 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1354 bool bErrorOnMissing = ext->required ? true : false;
1355 g_Extensions.LoadAutoExtension(path, bErrorOnMissing);
1360 /* Is this required? */
1363 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1364 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1366 pExt = g_Extensions.FindExtensionByName(name);
1368 /* :TODO: should we bind to unloaded extensions?
1369 * Currently the extension manager will ignore this.
1371 if (!pExt || !pExt->IsRunning(NULL, 0))
1375 UTIL_Format(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1381 g_Extensions.BindChildPlugin(pExt, pPlugin);
1386 IPluginFunction *pFunc;
1388 UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
1390 if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
1393 pFunc->Execute(&res);
1394 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1398 UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
1411 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1413 /* Second pass for extension requirements */
1414 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1419 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1424 /* Run another binding pass */
1425 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1427 /* Find any unbound natives. Right now, these are not allowed. */
1428 IPluginContext *pContext = pPlugin->GetBaseContext();
1429 uint32_t num = pContext->GetNativesNum();
1430 sp_native_t *native;
1431 for (unsigned int i=0; i<num; i++)
1433 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1437 if (native->status == SP_NATIVE_UNBOUND
1438 && native->name[0] != '@'
1439 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1443 UTIL_Format(error, maxlength, "Native \"%s\" was not found", native->name);
1449 /* Finish by telling all listeners */
1450 List<IPluginsListener *>::iterator iter;
1451 IPluginsListener *pListener;
1452 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1454 pListener = (*iter);
1455 pListener->OnPluginLoaded(pPlugin);
1458 /* Tell this plugin to finish initializing itself */
1459 pPlugin->Call_OnPluginStart();
1461 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1462 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_Natives.size())
1464 List<CPlugin *>::iterator pl_iter;
1466 for (pl_iter = m_plugins.begin();
1467 pl_iter != m_plugins.end();
1470 pOther = (*pl_iter);
1471 if ((pOther->GetStatus() == Plugin_Error
1472 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1473 || pOther->m_FakeNativesMissing)
1475 TryRefreshDependencies(pOther);
1477 else if ((pOther->GetStatus() == Plugin_Running
1478 || pOther->GetStatus() == Plugin_Paused)
1479 && pOther != pPlugin)
1481 List<NativeEntry *>::iterator nv_iter;
1482 for (nv_iter = pPlugin->m_Natives.begin();
1483 nv_iter != pPlugin->m_Natives.end();
1486 g_ShareSys.BindNativeToPlugin(pOther, (*nv_iter));
1492 /* Go through our libraries and tell other plugins they're added */
1493 List<String>::iterator s_iter;
1494 for (s_iter = pPlugin->m_Libraries.begin();
1495 s_iter != pPlugin->m_Libraries.end();
1498 OnLibraryAction((*s_iter).c_str(), true, false);
1501 /* :TODO: optimize? does this even matter? */
1502 pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
1507 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1509 assert(pPlugin->GetBaseContext() != NULL);
1511 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1513 List<String>::iterator lib_iter;
1514 List<String>::iterator req_iter;
1515 List<CPlugin *>::iterator pl_iter;
1517 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1520 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1523 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1525 if ((*req_iter) == (*lib_iter))
1533 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1538 /* Find any unbound natives
1539 * Right now, these are not allowed
1541 IPluginContext *pContext = pPlugin->GetBaseContext();
1542 uint32_t num = pContext->GetNativesNum();
1543 sp_native_t *native;
1544 for (unsigned int i=0; i<num; i++)
1546 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1550 if (native->status == SP_NATIVE_UNBOUND
1551 && native->name[0] != '@'
1552 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1554 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1559 if (pPlugin->GetStatus() == Plugin_Error)
1561 /* If we got here, all natives are okay again! */
1562 pPlugin->m_status = Plugin_Running;
1563 if (pPlugin->m_pRuntime->IsPaused())
1565 pPlugin->m_pRuntime->SetPauseState(false);
1566 _SetPauseState(pPlugin, false);
1571 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1573 CPlugin *pPlugin = (CPlugin *)plugin;
1575 /* This prevents removal during insertion or anything else weird */
1576 if (m_plugins.find(pPlugin) == m_plugins.end())
1581 IPluginContext *pContext = plugin->GetBaseContext();
1582 if (pContext != NULL && pContext->IsInExec())
1585 UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
1586 engine->ServerCommand(buffer);
1590 /* Remove us from the lookup table and linked list */
1591 m_plugins.remove(pPlugin);
1592 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1594 /* Go through our libraries and tell other plugins they're gone */
1595 List<String>::iterator s_iter;
1596 for (s_iter = pPlugin->m_Libraries.begin();
1597 s_iter != pPlugin->m_Libraries.end();
1600 OnLibraryAction((*s_iter).c_str(), true, true);
1603 List<IPluginsListener *>::iterator iter;
1604 IPluginsListener *pListener;
1606 if (pPlugin->GetStatus() <= Plugin_Error)
1609 pPlugin->Call_OnPluginEnd();
1611 /* Notify listeners of unloading */
1612 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1614 pListener = (*iter);
1615 pListener->OnPluginUnloaded(pPlugin);
1619 pPlugin->DropEverything();
1621 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1623 /* Notify listeners of destruction */
1624 pListener = (*iter);
1625 pListener->OnPluginDestroyed(pPlugin);
1628 /* Tell the plugin to delete itself */
1634 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1637 IPluginContext *pContext;
1639 pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
1641 if (pContext->GetKey(2, (void **)&pPlugin))
1649 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
1651 return (CPlugin *)FindPluginByContext(ctx);
1654 unsigned int CPluginManager::GetPluginCount()
1656 return m_plugins.size();
1659 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1661 m_listeners.push_back(listener);
1664 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1666 m_listeners.remove(listener);
1669 IPluginIterator *CPluginManager::GetPluginIterator()
1671 if (m_iters.empty())
1673 return new CPluginIterator(&m_plugins);
1675 CPluginIterator *iter = m_iters.front();
1682 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1687 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1689 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1690 size_t alias_len = 0;
1691 size_t local_len = 0;
1693 const char *ptr = alias;
1694 unsigned int alias_explicit_paths = 0;
1695 unsigned int alias_path_end = 0;
1696 while (*ptr != '\0')
1698 if (*ptr == '\\' || *ptr == '/')
1700 alias_explicit_paths++;
1701 alias_path_end = alias_len;
1707 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1709 /* Trailing slash is totally invalid here */
1714 unsigned int local_explicit_paths = 0;
1715 unsigned int local_path_end = 0;
1716 while (*ptr != '\0')
1718 if (*ptr == '\\' || *ptr == '/')
1720 local_explicit_paths++;
1721 local_path_end = local_len;
1727 /* If the alias has more explicit paths than the real path,
1728 * no match will be possible.
1730 if (alias_explicit_paths > local_explicit_paths)
1735 if (alias_explicit_paths)
1737 /* We need to find if the paths match now. For example, these should all match:
1739 * csdm optional/csdm
1740 * csdm/ban optional/crab/csdm/ban
1742 const char *aliasptr = alias;
1743 const char *localptr = localpath;
1747 if (*aliasptr != *localptr)
1749 /* We have to knock one path off */
1750 local_explicit_paths--;
1751 if (alias_explicit_paths > local_explicit_paths)
1753 /* Skip out if we're gonna have an impossible match */
1756 /* Eat up localptr tokens until we get a result */
1757 while (((localptr - localpath) < (int)local_path_end)
1759 && *localptr != '\\')
1763 /* Check if we hit the end of our searchable area.
1764 * This probably isn't possible because of the path
1765 * count check, but it's a good idea anyway.
1767 if ((localptr - localpath) >= (int)local_path_end)
1771 /* Consume the slash token */
1774 /* Reset the alias pointer so we can continue consuming */
1780 * This is safe because if localptr terminates early, aliasptr will too
1784 /* We should never reach the end of the string because of this check. */
1785 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1786 bool localend = (localptr - localpath) > (int)local_path_end;
1787 if (aliasend || localend)
1789 if (aliasend && localend)
1791 /* we matched, and we can break out now */
1795 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1800 /* If we got here, it's safe to compare the next two tokens */
1801 if (*localptr != *aliasptr)
1812 /* If we got here, it's time to compare filenames */
1813 const char *aliasptr = alias;
1814 const char *localptr = localpath;
1816 if (alias_explicit_paths)
1818 aliasptr = &alias[alias_path_end + 1];
1821 if (local_explicit_paths)
1823 localptr = &localpath[local_path_end + 1];
1828 if (*aliasptr == '*')
1830 /* First, see if this is the last character */
1831 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1833 /* If so, there's no need to match anything else */
1836 /* Otherwise, we need to search for an appropriate matching sequence in local.
1837 * Note that we only need to search up to the next asterisk.
1841 const char *local_orig = localptr;
1845 while (*aliasptr != '\0' && *aliasptr != '*')
1847 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1848 if (*aliasptr != *localptr)
1858 /* If we didn't get a match, we need to advance the search stream.
1859 * This will let us skip tokens while still searching for another match.
1861 localptr = ++local_orig;
1862 /* Make sure we don't go out of bounds */
1863 if (*localptr == '\0')
1874 /* If we got a match, move on to the next token */
1877 } else if (*aliasptr == '\0') {
1878 if (*localptr == '\0'
1880 strcmp(localptr, ".smx") == 0)
1886 } else if (*aliasptr != *localptr) {
1896 bool CPluginManager::IsLateLoadTime() const
1898 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1901 void CPluginManager::OnSourceModAllInitialized()
1903 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1906 g_HandleSys.InitAccessDefaults(NULL, &sec);
1908 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1909 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1911 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1912 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1914 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1916 g_ShareSys.AddInterface(NULL, this);
1919 void CPluginManager::OnSourceModShutdown()
1921 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1925 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1926 g_ShareSys.DestroyIdentType(g_PluginIdent);
1927 g_ShareSys.DestroyIdentity(m_MyIdent);
1930 ConfigResult CPluginManager::OnSourceModConfigChanged(const char *key,
1932 ConfigSource source,
1936 if (strcmp(key, "BlockBadPlugins") == 0) {
1937 if (strcasecmp(value, "yes") == 0)
1939 m_bBlockBadPlugins = true;
1940 } else if (strcasecmp(value, "no") == 0) {
1941 m_bBlockBadPlugins = false;
1943 UTIL_Format(error, maxlength, "Invalid value: must be \"yes\" or \"no\"");
1944 return ConfigResult_Reject;
1946 return ConfigResult_Accept;
1948 return ConfigResult_Ignore;
1951 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1953 /* We don't care about the internal object, actually */
1956 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
1958 *pSize = ((CPlugin *)object)->CalcMemUsage();
1962 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1970 sec.pIdentity = m_MyIdent;
1972 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1985 CPlugin *CPluginManager::GetPluginByOrder(int num)
1987 if (num < 1 || num > (int)GetPluginCount())
1995 SourceHook::List<CPlugin *>::iterator iter;
1996 for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
2003 const char *CPluginManager::GetStatusText(PluginStatus st)
2007 case Plugin_Running:
2013 case Plugin_Uncompiled:
2014 return "Uncompiled";
2015 case Plugin_BadLoad:
2025 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
2027 int argcount = command.ArgC();
2030 const char *cmd = command.Arg(2);
2031 if (strcmp(cmd, "list") == 0)
2034 unsigned int id = 1;
2035 int plnum = GetPluginCount();
2039 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
2044 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
2048 SourceHook::List<CPlugin *>::iterator iter;
2049 SourceHook::List<CPlugin *> m_FailList;
2051 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
2054 assert(pl->GetStatus() != Plugin_Created);
2056 const sm_plugininfo_t *info = pl->GetPublicInfo();
2057 if (pl->GetStatus() != Plugin_Running && !pl->IsSilentlyFailed())
2059 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
2061 if (pl->GetStatus() <= Plugin_Error)
2063 /* Plugin has failed to load. */
2064 m_FailList.push_back(pl);
2069 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
2071 if (pl->GetStatus() < Plugin_Created)
2073 if (pl->IsSilentlyFailed())
2074 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " Disabled:");
2075 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2076 if (IS_STR_FILLED(info->version))
2078 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
2080 if (IS_STR_FILLED(info->author))
2082 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
2087 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
2089 g_RootMenu.ConsolePrint("%s", buffer);
2092 if (!m_FailList.empty())
2094 g_RootMenu.ConsolePrint("Load Errors:");
2096 SourceHook::List<CPlugin *>::iterator _iter;
2100 for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
2102 pl = (CPlugin *)*_iter;
2103 g_RootMenu.ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
2109 else if (strcmp(cmd, "load") == 0)
2113 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
2119 const char *filename = command.Arg(3);
2121 char pluginfile[256];
2122 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
2123 g_SourceMod.BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
2125 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
2129 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
2135 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
2139 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
2144 else if (strcmp(cmd, "unload") == 0)
2148 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
2154 const char *arg = command.Arg(3);
2155 int id = strtol(arg, &end, 10);
2159 pl = GetPluginByOrder(id);
2162 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2168 char pluginfile[256];
2169 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2170 g_SourceMod.BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2172 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2174 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2179 char name[PLATFORM_MAX_PATH];
2181 if (pl->GetStatus() < Plugin_Created)
2183 const sm_plugininfo_t *info = pl->GetPublicInfo();
2184 UTIL_Format(name, sizeof(name), (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2188 UTIL_Format(name, sizeof(name), "%s", pl->GetFilename());
2191 if (UnloadPlugin(pl))
2193 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
2197 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
2202 else if (strcmp(cmd, "unload_all") == 0)
2204 g_PluginSys.UnloadAll();
2205 g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
2208 else if (strcmp(cmd, "load_lock") == 0)
2210 if (m_LoadingLocked)
2212 g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
2216 m_LoadingLocked = true;
2217 g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
2221 else if (strcmp(cmd, "load_unlock") == 0)
2223 if (m_LoadingLocked)
2225 m_LoadingLocked = false;
2226 g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
2230 g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
2234 else if (strcmp(cmd, "info") == 0)
2238 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2244 const char *arg = command.Arg(3);
2245 int id = strtol(arg, &end, 10);
2249 pl = GetPluginByOrder(id);
2252 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2258 char pluginfile[256];
2259 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2260 g_SourceMod.BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2262 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2264 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2269 const sm_plugininfo_t *info = pl->GetPublicInfo();
2271 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2272 if (pl->GetStatus() <= Plugin_Error)
2274 if (IS_STR_FILLED(info->name))
2276 if (IS_STR_FILLED(info->description))
2278 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2280 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2283 if (IS_STR_FILLED(info->author))
2285 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2287 if (IS_STR_FILLED(info->version))
2289 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2291 if (IS_STR_FILLED(info->url))
2293 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2295 if (pl->GetStatus() == Plugin_Error)
2297 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2301 if (pl->GetStatus() == Plugin_Running)
2303 g_RootMenu.ConsolePrint(" Status: running");
2307 g_RootMenu.ConsolePrint(" Status: not running");
2310 const char *typestr = "";
2311 switch (pl->GetType())
2313 case PluginType_MapUpdated:
2314 typestr = "Map Change if Updated";
2316 case PluginType_MapOnly:
2317 typestr = "Map Change";
2319 case PluginType_Private:
2320 case PluginType_Global:
2325 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2327 if (pl->m_FileVersion >= 3)
2329 g_RootMenu.ConsolePrint(" Timestamp: %s", pl->m_DateTime);
2332 unsigned char *pCodeHash = pl->m_pRuntime->GetCodeHash();
2333 unsigned char *pDataHash = pl->m_pRuntime->GetDataHash();
2335 char combinedHash[33];
2336 for (int i = 0; i < 16; i++)
2337 UTIL_Format(combinedHash + (i * 2), 3, "%02x", pCodeHash[i] ^ pDataHash[i]);
2339 g_RootMenu.ConsolePrint(" Hash: %s", combinedHash);
2343 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2344 if (pl->GetStatus() < Plugin_Created)
2346 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2347 info->name ? info->name : "<none>",
2348 info->version ? info->version : "<none>");
2349 if (IS_STR_FILLED(info->url))
2351 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2358 else if (strcmp(cmd, "refresh") == 0)
2360 g_SourceMod.DoGlobalPluginLoads();
2361 g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
2364 else if (strcmp(cmd, "reload") == 0)
2368 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
2374 const char *arg = command.Arg(3);
2375 int id = strtol(arg, &end, 10);
2379 pl = GetPluginByOrder(id);
2382 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2388 char pluginfile[256];
2389 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2390 g_SourceMod.BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2392 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2394 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2399 char name[PLATFORM_MAX_PATH];
2400 const sm_plugininfo_t *info = pl->GetPublicInfo();
2401 if (pl->GetStatus() <= Plugin_Paused)
2402 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2404 strcpy(name, pl->GetFilename());
2406 if (ReloadPlugin(pl))
2408 g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
2412 g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
2419 /* Draw the main menu */
2420 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2421 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2422 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2423 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2424 g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
2425 g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
2426 g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
2427 g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
2428 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2429 g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
2432 bool CPluginManager::ReloadPlugin(CPlugin *pl)
2434 List<CPlugin *>::iterator iter;
2435 char filename[PLATFORM_MAX_PATH];
2441 strcpy(filename, pl->m_filename);
2442 ptype = pl->GetType();
2444 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
2452 if (!UnloadPlugin(pl))
2456 if (!(newpl=LoadPlugin(filename, true, ptype, NULL, 0, &wasloaded)))
2461 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2463 if ((*iter) == (CPlugin *)newpl)
2465 m_plugins.erase(iter);
2471 for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
2474 m_plugins.insert(iter, (CPlugin *)newpl);
2479 void CPluginManager::ReloadOrUnloadPlugins()
2481 /* If we're in a load lock, just skip this whole bit. */
2482 if (m_LoadingLocked)
2487 List<CPlugin *>::iterator iter;
2488 List<CPlugin *> tmp_list = m_plugins;
2492 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2495 if (pl->GetType() == PluginType_MapOnly)
2497 UnloadPlugin((IPlugin *)pl);
2499 else if (pl->GetType() == PluginType_MapUpdated)
2501 t = pl->GetFileTimeStamp();
2502 if (!t || t > pl->GetTimeStamp())
2504 pl->SetTimeStamp(t);
2505 UnloadPlugin((IPlugin *)pl);
2511 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2513 List<IPluginsListener *>::iterator iter;
2514 IPluginsListener *pListener;
2515 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2517 pListener = (*iter);
2518 pListener->OnPluginPauseChange(pl, paused);
2522 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2524 List<CPlugin *>::iterator iter;
2526 IPluginFunction *pFunction;
2528 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2532 if (pPlugin->GetStatus() <= Plugin_Paused)
2534 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2538 pForward->AddFunction(pFunction);
2544 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2546 if (pToken->type != g_PluginIdent)
2551 return (CPlugin *)(pToken->ptr);
2554 void CPluginManager::OnLibraryAction(const char *lib, bool is_a_plugin, bool drop)
2556 List<CPlugin *>::iterator iter;
2573 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2575 for (iter=m_plugins.begin();
2576 iter!=m_plugins.end();
2579 CPlugin *pl = (*iter);
2580 if (pl->GetStatus() != Plugin_Running)
2584 IPluginContext *pContext = pl->GetBaseContext();
2585 IPluginFunction *pf = pContext->GetFunctionByName(name);
2590 uint32_t num_vars = pContext->GetPubVarsNum();
2591 for (uint32_t i=0; i<num_vars; i++)
2593 sp_pubvar_t *pubvar;
2594 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2598 if (is_a_plugin && strncmp(pubvar->name, "__pl_", 5) == 0)
2600 plc = (_pl *)pubvar->offs;
2606 pContext->LocalToString(plc->name, &str);
2607 if (strcmp(str, lib) != 0)
2611 pf->PushString(lib);
2614 else if (!is_a_plugin && strncmp(pubvar->name, "__ext_", 6) == 0)
2616 ext = (_ext *)pubvar->offs;
2622 pContext->LocalToString(ext->name, &str);
2623 if (strcmp(str, lib) != 0)
2627 pf->PushString(lib);
2634 bool CPluginManager::LibraryExists(const char *lib)
2636 List<CPlugin *>::iterator iter;
2638 for (iter=m_plugins.begin();
2639 iter!=m_plugins.end();
2642 CPlugin *pl = (*iter);
2643 if (pl->GetStatus() != Plugin_Running)
2647 List<String>::iterator s_iter;
2648 for (s_iter = pl->m_Libraries.begin();
2649 s_iter != pl->m_Libraries.end();
2652 if ((*s_iter).compare(lib) == 0)
2662 void CPluginManager::AllPluginsLoaded()
2664 List<CPlugin *>::iterator iter;
2667 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2670 pl->Call_OnAllPluginsLoaded();
2674 void CPluginManager::UnloadAll()
2676 List<CPlugin *>::iterator iter;
2677 while ( (iter = m_plugins.begin()) != m_plugins.end() )
2679 UnloadPlugin((*iter));
2683 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
2686 List<CPlugin *>::iterator iter;
2688 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
2699 CPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
2705 id = strtol(arg, &end, 10);
2709 pl = GetPluginByOrder(id);
2717 char pluginfile[256];
2718 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2719 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2721 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2730 void CPluginManager::OnSourceModMaxPlayersChanged(int newvalue)
2732 SyncMaxClients(newvalue);
2735 void CPluginManager::SyncMaxClients(int max_clients)
2737 List<CPlugin *>::iterator iter;
2739 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2741 (*iter)->SyncMaxClients(max_clients);
2745 void CPluginManager::ListPluginsToClient(CPlayer *player, const CCommand &args)
2748 unsigned int id = 0;
2749 int plnum = GetPluginCount();
2750 edict_t *e = player->GetEdict();
2751 unsigned int start = 0;
2755 ClientConsolePrint(e, "[SM] No plugins found.");
2759 if (args.ArgC() > 2)
2761 start = atoi(args.Arg(2));
2765 SourceHook::List<CPlugin *>::iterator iter;
2766 SourceHook::List<CPlugin *> m_FailList;
2768 for (iter = m_plugins.begin();
2769 iter != m_plugins.end();
2774 if (pl->GetStatus() != Plugin_Running)
2779 /* Count valid plugins */
2786 if (id - start > 10)
2792 const sm_plugininfo_t *info = pl->GetPublicInfo();
2793 len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2794 if (IS_STR_FILLED(info->version))
2796 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
2798 if (IS_STR_FILLED(info->author))
2800 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
2804 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
2806 ClientConsolePrint(e, "%s", buffer);
2809 /* See if we can get more plugins */
2810 while (iter != m_plugins.end())
2812 if ((*iter)->GetStatus() == Plugin_Running)
2818 /* Do we actually have more plugins? */
2819 if (iter != m_plugins.end())
2821 ClientConsolePrint(e, "To see more, type \"sm plugins %d\"", id);