3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include "PluginSys.h"
35 #include "LibrarySys.h"
36 #include "HandleSys.h"
37 #include "ForwardSys.h"
38 #include "sourcemm_api.h"
39 #include "sourcemod.h"
40 #include "TextParsers.h"
42 #include "ExtensionSys.h"
43 #include "sm_srvcmds.h"
44 #include "sm_stringutil.h"
45 #include "ConCmdManager.h"
46 #include "PlayerManager.h"
47 #include "CoreConfig.h"
48 #include "Translator.h"
50 CPluginManager g_PluginSys;
51 HandleType_t g_PluginType = 0;
52 IdentityType_t g_PluginIdent = 0;
54 CPlugin::CPlugin(const char *file)
56 static int MySerial = 0;
58 m_type = PluginType_Private;
59 m_status = Plugin_Uncompiled;
60 m_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 >= 3)
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 > 4)
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 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
391 if (m_status != Plugin_Created)
396 m_status = Plugin_Loaded;
400 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad");
407 pFunction->PushCell(m_handle);
408 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
409 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
410 pFunction->PushCell(maxlength);
411 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
416 if (!result || m_status != Plugin_Loaded)
424 void *CPlugin::GetPluginStructure()
429 IPluginContext *CPlugin::GetBaseContext()
431 if (m_pRuntime == NULL)
436 return m_pRuntime->GetDefaultContext();
439 sp_context_t *CPlugin::GetContext()
444 const char *CPlugin::GetFilename()
449 PluginType CPlugin::GetType()
454 const sm_plugininfo_t *CPlugin::GetPublicInfo()
456 if (GetStatus() >= Plugin_Created)
463 unsigned int CPlugin::GetSerial()
468 PluginStatus CPlugin::GetStatus()
473 bool CPlugin::IsDebugging()
475 if (m_pRuntime == NULL)
483 void CPlugin::LibraryActions(bool dropping)
485 List<String>::iterator iter;
486 for (iter = m_Libraries.begin();
487 iter != m_Libraries.end();
490 g_PluginSys.OnLibraryAction((*iter).c_str(), true, dropping);
494 bool CPlugin::SetPauseState(bool paused)
496 if (paused && GetStatus() != Plugin_Running)
499 } else if (!paused && GetStatus() != Plugin_Paused) {
505 LibraryActions(true);
508 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginPauseChange");
512 pFunction->PushCell(paused ? 1 : 0);
513 pFunction->Execute(&result);
518 m_status = Plugin_Paused;
519 m_pRuntime->SetPauseState(true);
521 m_status = Plugin_Running;
522 m_pRuntime->SetPauseState(false);
525 g_PluginSys._SetPauseState(this, paused);
529 LibraryActions(false);
535 IdentityToken_t *CPlugin::GetIdentity()
540 bool CPlugin::IsRunnable()
542 return (m_status <= Plugin_Paused) ? true : false;
545 time_t CPlugin::GetFileTimeStamp()
547 char path[PLATFORM_MAX_PATH];
548 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
549 #ifdef PLATFORM_WINDOWS
551 if (_stat(path, &s) != 0)
552 #elif defined PLATFORM_POSIX
554 if (stat(path, &s) != 0)
565 time_t CPlugin::GetTimeStamp()
570 void CPlugin::SetTimeStamp(time_t t)
575 IPhraseCollection *CPlugin::GetPhrases()
580 void CPlugin::DependencyDropped(CPlugin *pOwner)
587 List<String>::iterator reqlib_iter;
588 List<String>::iterator lib_iter;
589 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
591 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
593 if ((*reqlib_iter) == (*lib_iter))
595 m_LibraryMissing = true;
600 List<NativeEntry *>::iterator iter;
601 NativeEntry *pNative;
604 unsigned int unbound = 0;
606 for (iter = pOwner->m_Natives.begin();
607 iter != pOwner->m_Natives.end();
611 /* Find this native! */
612 if (m_pRuntime->FindNativeByName(pNative->name, &idx) != SP_ERROR_NONE)
617 m_pRuntime->GetNativeByIndex(idx, &native);
619 native->status = SP_NATIVE_UNBOUND;
625 m_FakeNativesMissing = true;
628 /* :IDEA: in the future, add native trapping? */
629 if (m_FakeNativesMissing || m_LibraryMissing)
631 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
635 unsigned int CPlugin::GetConfigCount()
637 return (unsigned int)m_configs.size();
640 AutoConfig *CPlugin::GetConfig(unsigned int i)
642 if (i >= GetConfigCount())
650 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
652 /* Do a check for duplicates to prevent double-execution */
653 for (size_t i = 0; i < m_configs.size(); i++)
655 if (m_configs[i]->autocfg.compare(cfg) == 0
656 && m_configs[i]->folder.compare(folder) == 0
657 && m_configs[i]->create == autoCreate)
663 AutoConfig *c = new AutoConfig;
667 c->create = autoCreate;
669 m_configs.push_back(c);
672 void CPlugin::DropEverything()
675 List<CPlugin *>::iterator iter;
676 List<WeakNative>::iterator wk_iter;
678 /* Tell everyone that depends on us that we're about to drop */
679 for (iter = m_Dependents.begin();
680 iter != m_Dependents.end();
684 pOther->DependencyDropped(this);
687 /* Note: we don't care about things we depend on.
688 * The reason is that extensions have their own cleanup
689 * code for plugins. Although the "right" design would be
690 * to centralize that here, i'm omitting it for now. Thus,
691 * the code below to walk the plugins list will suffice.
694 /* Other plugins could be holding weak references that were
695 * added by us. We need to clean all of those up now.
697 for (iter = g_PluginSys.m_plugins.begin();
698 iter != g_PluginSys.m_plugins.end();
701 (*iter)->DropRefsTo(this);
704 /* Proceed with the rest of the necessities. */
705 CNativeOwner::DropEverything();
708 bool CPlugin::AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func)
712 if ((pEntry = g_ShareSys.AddFakeNative(pFunc, name, func)) == NULL)
717 m_Natives.push_back(pEntry);
726 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
732 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
737 bool CPluginManager::CPluginIterator::MorePlugins()
739 return (current != mylist->end());
742 void CPluginManager::CPluginIterator::NextPlugin()
747 void CPluginManager::CPluginIterator::Release()
749 g_PluginSys.ReleaseIterator(this);
752 CPluginManager::CPluginIterator::~CPluginIterator()
756 void CPluginManager::CPluginIterator::Reset()
758 current = mylist->begin();
765 CPluginManager::CPluginManager()
767 m_LoadLookup = sm_trie_create();
768 m_AllPluginsLoaded = false;
770 m_LoadingLocked = false;
773 CPluginManager::~CPluginManager()
776 * Ignore the fact that there might be plugins in the cache.
777 * This usually means that Core is not being unloaded properly, and everything
778 * will crash anyway. YAY
780 sm_trie_destroy(m_LoadLookup);
782 CStack<CPluginManager::CPluginIterator *>::iterator iter;
783 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
790 void CPluginManager::Shutdown()
792 List<CPlugin *>::iterator iter;
794 while ((iter = m_plugins.begin()) != m_plugins.end())
800 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
802 /* First read in the database of plugin settings */
805 m_AllPluginsLoaded = false;
806 if ((err=textparsers->ParseFile_SMC(config, &m_PluginInfo, &states)) != SMCError_Okay)
808 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
809 const char *err_msg = textparsers->GetSMCErrorString(err);
812 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
816 LoadPluginsFromDir(basedir, NULL);
819 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
821 char base_path[PLATFORM_MAX_PATH];
823 /* Form the current path to start reading from */
824 if (localpath == NULL)
826 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
828 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
831 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
836 g_LibSys.GetPlatformError(error, sizeof(error));
837 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
838 g_Logger.LogError("[SM] Platform returned error: %s", error);
842 while (dir->MoreFiles())
844 if (dir->IsEntryDirectory()
845 && (strcmp(dir->GetEntryName(), ".") != 0)
846 && (strcmp(dir->GetEntryName(), "..") != 0)
847 && (strcmp(dir->GetEntryName(), "disabled") != 0)
848 && (strcmp(dir->GetEntryName(), "optional") != 0))
850 char new_local[PLATFORM_MAX_PATH];
851 if (localpath == NULL)
853 /* If no path yet, don't add a former slash */
854 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
856 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
858 LoadPluginsFromDir(basedir, new_local);
859 } else if (dir->IsEntryFile()) {
860 const char *name = dir->GetEntryName();
861 size_t len = strlen(name);
863 && strcmp(&name[len-4], ".smx") == 0)
865 /* If the filename matches, load the plugin */
866 char plugin[PLATFORM_MAX_PATH];
867 if (localpath == NULL)
869 snprintf(plugin, sizeof(plugin), "%s", name);
871 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
873 LoadAutoPlugin(plugin);
878 g_LibSys.CloseDirectory(dir);
881 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
885 return LoadRes_NeverLoad;
889 bool no_load = false;
890 PluginSettings *pset;
891 unsigned int setcount = m_PluginInfo.GetSettingsNum();
892 for (unsigned int i=0; i<setcount; i++)
894 if ((pset = m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
898 if (pset->blockload_val)
906 * Does this plugin already exist?
909 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
911 /* Check to see if we should try reloading it */
912 if (pPlugin->GetStatus() == Plugin_BadLoad
913 || pPlugin->GetStatus() == Plugin_Error
914 || pPlugin->GetStatus() == Plugin_Failed
917 UnloadPlugin(pPlugin);
925 return LoadRes_AlreadyLoaded;
931 return LoadRes_NeverLoad;
934 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
936 assert(pPlugin != NULL);
938 pPlugin->m_type = PluginType_MapUpdated;
940 ICompilation *co = NULL;
942 if (pPlugin->m_status == Plugin_Uncompiled)
944 co = g_pSourcePawn2->StartCompilation();
947 for (unsigned int i=0; i<setcount; i++)
949 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
953 pPlugin->m_type = pset->type_val;
956 for (unsigned int j=0; j<pset->opts_num; j++)
958 const char *key, *val;
959 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
964 if ((err = co->SetOption(key, val)) == SP_ERROR_NONE)
968 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
978 /* Do the actual compiling */
981 char fullpath[PLATFORM_MAX_PATH];
982 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", pPlugin->m_filename);
984 pPlugin->m_pRuntime = g_pSourcePawn2->LoadPlugin(co, fullpath, &err);
985 if (pPlugin->m_pRuntime == NULL)
989 "Unable to load plugin (error %d: %s)",
991 g_pSourcePawn2->GetErrorString(err));
992 pPlugin->m_status = Plugin_BadLoad;
996 if (pPlugin->UpdateInfo())
998 pPlugin->m_status = Plugin_Created;
1002 UTIL_Format(error, maxlength, "%s", pPlugin->m_errormsg);
1007 /* Get the status */
1008 if (pPlugin->GetStatus() == Plugin_Created)
1010 /* First native pass - add anything from Core */
1011 g_ShareSys.BindNativesToPlugin(pPlugin, true);
1012 pPlugin->InitIdentity();
1013 if (pPlugin->Call_AskPluginLoad(error, maxlength))
1015 /* Autoload any modules */
1016 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
1020 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1024 /* Save the time stamp */
1025 time_t t = pPlugin->GetFileTimeStamp();
1026 pPlugin->SetTimeStamp(t);
1033 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
1036 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
1042 if ((res=_LoadPlugin(&pl, path, true, type, error, maxlength)) == LoadRes_Failure)
1048 if (res == LoadRes_AlreadyLoaded)
1054 if (res == LoadRes_NeverLoad)
1056 if (m_LoadingLocked)
1058 UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect");
1062 UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
1069 /* Run second pass if we need to */
1070 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
1072 if (!RunSecondPass(pl, error, maxlength))
1077 pl->Call_OnAllPluginsLoaded();
1083 void CPluginManager::LoadAutoPlugin(const char *plugin)
1087 char error[255] = "Unknown error";
1089 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
1091 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
1093 pl->GetStatus() == Plugin_BadLoad ? Plugin_BadLoad : Plugin_Failed,
1098 if (res == LoadRes_Successful || res == LoadRes_Failure)
1104 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1106 List<IPluginsListener *>::iterator iter;
1107 IPluginsListener *pListener;
1109 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1111 pListener = (*iter);
1112 pListener->OnPluginCreated(pPlugin);
1115 m_plugins.push_back(pPlugin);
1116 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1119 void CPluginManager::LoadAll_SecondPass()
1121 List<CPlugin *>::iterator iter;
1125 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1128 if (pPlugin->GetStatus() == Plugin_Loaded)
1131 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1133 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1134 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1139 m_AllPluginsLoaded = true;
1142 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1151 IPluginContext *pBase = pPlugin->GetBaseContext();
1152 uint32_t num = pBase->GetPubVarsNum();
1153 sp_pubvar_t *pubvar;
1155 char pathfile[PLATFORM_MAX_PATH];
1157 for (uint32_t i=0; i<num; i++)
1159 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1163 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1165 pl = (_pl *)pubvar->offs;
1166 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1170 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1174 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1175 if (strcmp(pathfile, file) == 0)
1179 if (pl->required == false)
1181 IPluginFunction *pFunc;
1183 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1184 if ((pFunc=pBase->GetFunctionByName(buffer)))
1187 pFunc->Execute(&res);
1188 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1192 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1200 /* Check that we aren't registering the same library twice */
1201 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1203 pPlugin->m_RequiredLibs.push_back(name);
1209 List<CPlugin *>::iterator iter;
1212 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1215 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1225 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1236 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1238 /* Find any extensions this plugin needs */
1247 IPluginContext *pBase = pPlugin->GetBaseContext();
1248 uint32_t num = pBase->GetPubVarsNum();
1249 sp_pubvar_t *pubvar;
1251 char path[PLATFORM_MAX_PATH];
1253 for (uint32_t i=0; i<num; i++)
1255 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1259 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1261 ext = (_ext *)pubvar->offs;
1262 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1266 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1272 /* Attempt to auto-load if necessary */
1275 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1276 g_Extensions.LoadAutoExtension(path);
1281 /* Is this required? */
1284 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1285 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1287 pExt = g_Extensions.FindExtensionByName(name);
1289 /* :TODO: should we bind to unloaded extensions?
1290 * Currently the extension manager will ignore this.
1292 if (!pExt || !pExt->IsRunning(NULL, 0))
1296 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1302 g_Extensions.BindChildPlugin(pExt, pPlugin);
1307 IPluginFunction *pFunc;
1309 UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
1311 if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
1314 pFunc->Execute(&res);
1315 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1319 UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
1332 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1334 /* Second pass for extension requirements */
1335 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1340 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1345 /* Run another binding pass */
1346 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1348 /* Find any unbound natives. Right now, these are not allowed. */
1349 IPluginContext *pContext = pPlugin->GetBaseContext();
1350 uint32_t num = pContext->GetNativesNum();
1351 sp_native_t *native;
1352 for (unsigned int i=0; i<num; i++)
1354 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1358 if (native->status == SP_NATIVE_UNBOUND
1359 && native->name[0] != '@'
1360 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1364 snprintf(error, maxlength, "Native \"%s\" was not found", native->name);
1370 /* Finish by telling all listeners */
1371 List<IPluginsListener *>::iterator iter;
1372 IPluginsListener *pListener;
1373 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1375 pListener = (*iter);
1376 pListener->OnPluginLoaded(pPlugin);
1379 /* Tell this plugin to finish initializing itself */
1380 pPlugin->Call_OnPluginStart();
1382 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1383 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_Natives.size())
1385 List<CPlugin *>::iterator pl_iter;
1387 for (pl_iter = m_plugins.begin();
1388 pl_iter != m_plugins.end();
1391 pOther = (*pl_iter);
1392 if ((pOther->GetStatus() == Plugin_Error
1393 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1394 || pOther->m_FakeNativesMissing)
1396 TryRefreshDependencies(pOther);
1398 else if ((pOther->GetStatus() == Plugin_Running
1399 || pOther->GetStatus() == Plugin_Paused)
1400 && pOther != pPlugin)
1402 List<NativeEntry *>::iterator nv_iter;
1403 for (nv_iter = pPlugin->m_Natives.begin();
1404 nv_iter != pPlugin->m_Natives.end();
1407 g_ShareSys.BindNativeToPlugin(pOther, (*nv_iter));
1413 /* Go through our libraries and tell other plugins they're added */
1414 List<String>::iterator s_iter;
1415 for (s_iter = pPlugin->m_Libraries.begin();
1416 s_iter != pPlugin->m_Libraries.end();
1419 OnLibraryAction((*s_iter).c_str(), true, false);
1422 /* :TODO: optimize? does this even matter? */
1423 pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
1428 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1430 assert(pPlugin->GetBaseContext() != NULL);
1432 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1434 List<String>::iterator lib_iter;
1435 List<String>::iterator req_iter;
1436 List<CPlugin *>::iterator pl_iter;
1438 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1441 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1444 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1446 if ((*req_iter) == (*lib_iter))
1454 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1459 /* Find any unbound natives
1460 * Right now, these are not allowed
1462 IPluginContext *pContext = pPlugin->GetBaseContext();
1463 uint32_t num = pContext->GetNativesNum();
1464 sp_native_t *native;
1465 for (unsigned int i=0; i<num; i++)
1467 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1471 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1473 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1478 if (pPlugin->GetStatus() == Plugin_Error)
1480 /* If we got here, all natives are okay again! */
1481 pPlugin->m_status = Plugin_Running;
1482 if (pPlugin->m_pRuntime->IsPaused())
1484 pPlugin->m_pRuntime->SetPauseState(false);
1485 _SetPauseState(pPlugin, false);
1490 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1492 CPlugin *pPlugin = (CPlugin *)plugin;
1494 /* This prevents removal during insertion or anything else weird */
1495 if (m_plugins.find(pPlugin) == m_plugins.end())
1500 IPluginContext *pContext = plugin->GetBaseContext();
1501 if (pContext != NULL && pContext->IsInExec())
1504 UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
1505 engine->ServerCommand(buffer);
1509 /* Remove us from the lookup table and linked list */
1510 m_plugins.remove(pPlugin);
1511 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1513 /* Go through our libraries and tell other plugins they're gone */
1514 List<String>::iterator s_iter;
1515 for (s_iter = pPlugin->m_Libraries.begin();
1516 s_iter != pPlugin->m_Libraries.end();
1519 OnLibraryAction((*s_iter).c_str(), true, true);
1522 List<IPluginsListener *>::iterator iter;
1523 IPluginsListener *pListener;
1525 if (pPlugin->GetStatus() <= Plugin_Error)
1527 /* Notify listeners of unloading */
1528 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1530 pListener = (*iter);
1531 pListener->OnPluginUnloaded(pPlugin);
1534 pPlugin->Call_OnPluginEnd();
1537 pPlugin->DropEverything();
1539 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1541 /* Notify listeners of destruction */
1542 pListener = (*iter);
1543 pListener->OnPluginDestroyed(pPlugin);
1546 /* Tell the plugin to delete itself */
1552 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1555 IPluginContext *pContext;
1557 pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
1559 if (pContext->GetKey(2, (void **)&pPlugin))
1567 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
1569 return (CPlugin *)FindPluginByContext(ctx);
1572 unsigned int CPluginManager::GetPluginCount()
1574 return m_plugins.size();
1577 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1579 m_listeners.push_back(listener);
1582 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1584 m_listeners.remove(listener);
1587 IPluginIterator *CPluginManager::GetPluginIterator()
1589 if (m_iters.empty())
1591 return new CPluginIterator(&m_plugins);
1593 CPluginIterator *iter = m_iters.front();
1600 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1605 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1607 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1608 size_t alias_len = 0;
1609 size_t local_len = 0;
1611 const char *ptr = alias;
1612 unsigned int alias_explicit_paths = 0;
1613 unsigned int alias_path_end = 0;
1614 while (*ptr != '\0')
1616 if (*ptr == '\\' || *ptr == '/')
1618 alias_explicit_paths++;
1619 alias_path_end = alias_len;
1625 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1627 /* Trailing slash is totally invalid here */
1632 unsigned int local_explicit_paths = 0;
1633 unsigned int local_path_end = 0;
1634 while (*ptr != '\0')
1636 if (*ptr == '\\' || *ptr == '/')
1638 local_explicit_paths++;
1639 local_path_end = local_len;
1645 /* If the alias has more explicit paths than the real path,
1646 * no match will be possible.
1648 if (alias_explicit_paths > local_explicit_paths)
1653 if (alias_explicit_paths)
1655 /* We need to find if the paths match now. For example, these should all match:
1657 * csdm optional/csdm
1658 * csdm/ban optional/crab/csdm/ban
1660 const char *aliasptr = alias;
1661 const char *localptr = localpath;
1665 if (*aliasptr != *localptr)
1667 /* We have to knock one path off */
1668 local_explicit_paths--;
1669 if (alias_explicit_paths > local_explicit_paths)
1671 /* Skip out if we're gonna have an impossible match */
1674 /* Eat up localptr tokens until we get a result */
1675 while (((localptr - localpath) < (int)local_path_end)
1677 && *localptr != '\\')
1681 /* Check if we hit the end of our searchable area.
1682 * This probably isn't possible because of the path
1683 * count check, but it's a good idea anyway.
1685 if ((localptr - localpath) >= (int)local_path_end)
1689 /* Consume the slash token */
1692 /* Reset the alias pointer so we can continue consuming */
1698 * This is safe because if localptr terminates early, aliasptr will too
1702 /* We should never reach the end of the string because of this check. */
1703 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1704 bool localend = (localptr - localpath) > (int)local_path_end;
1705 if (aliasend || localend)
1707 if (aliasend && localend)
1709 /* we matched, and we can break out now */
1713 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1718 /* If we got here, it's safe to compare the next two tokens */
1719 if (*localptr != *aliasptr)
1730 /* If we got here, it's time to compare filenames */
1731 const char *aliasptr = alias;
1732 const char *localptr = localpath;
1734 if (alias_explicit_paths)
1736 aliasptr = &alias[alias_path_end + 1];
1739 if (local_explicit_paths)
1741 localptr = &localpath[local_path_end + 1];
1746 if (*aliasptr == '*')
1748 /* First, see if this is the last character */
1749 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1751 /* If so, there's no need to match anything else */
1754 /* Otherwise, we need to search for an appropriate matching sequence in local.
1755 * Note that we only need to search up to the next asterisk.
1759 const char *local_orig = localptr;
1763 while (*aliasptr != '\0' && *aliasptr != '*')
1765 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1766 if (*aliasptr != *localptr)
1776 /* If we didn't get a match, we need to advance the search stream.
1777 * This will let us skip tokens while still searching for another match.
1779 localptr = ++local_orig;
1780 /* Make sure we don't go out of bounds */
1781 if (*localptr == '\0')
1792 /* If we got a match, move on to the next token */
1795 } else if (*aliasptr == '\0') {
1796 if (*localptr == '\0'
1798 strcmp(localptr, ".smx") == 0)
1804 } else if (*aliasptr != *localptr) {
1814 bool CPluginManager::IsLateLoadTime() const
1816 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1819 void CPluginManager::OnSourceModAllInitialized()
1821 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1824 g_HandleSys.InitAccessDefaults(NULL, &sec);
1826 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1827 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1829 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1830 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1832 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1834 g_ShareSys.AddInterface(NULL, this);
1837 void CPluginManager::OnSourceModShutdown()
1839 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1843 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1844 g_ShareSys.DestroyIdentType(g_PluginIdent);
1845 g_ShareSys.DestroyIdentity(m_MyIdent);
1848 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1850 /* We don't care about the internal object, actually */
1853 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
1855 *pSize = ((CPlugin *)object)->CalcMemUsage();
1859 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1867 sec.pIdentity = m_MyIdent;
1869 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1882 CPlugin *CPluginManager::GetPluginByOrder(int num)
1884 if (num < 1 || num > (int)GetPluginCount())
1892 SourceHook::List<CPlugin *>::iterator iter;
1893 for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
1900 const char *CPluginManager::GetStatusText(PluginStatus st)
1904 case Plugin_Running:
1910 case Plugin_Uncompiled:
1911 return "Uncompiled";
1912 case Plugin_BadLoad:
1922 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
1924 int argcount = command.ArgC();
1927 const char *cmd = command.Arg(2);
1928 if (strcmp(cmd, "list") == 0)
1931 unsigned int id = 1;
1932 int plnum = GetPluginCount();
1936 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1941 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1945 SourceHook::List<CPlugin *>::iterator iter;
1946 SourceHook::List<CPlugin *> m_FailList;
1948 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
1951 assert(pl->GetStatus() != Plugin_Created);
1953 const sm_plugininfo_t *info = pl->GetPublicInfo();
1954 if (pl->GetStatus() != Plugin_Running)
1956 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1958 if (pl->GetStatus() <= Plugin_Error)
1960 /* Plugin has failed to load. */
1961 m_FailList.push_back(pl);
1966 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1968 if (pl->GetStatus() < Plugin_Created)
1970 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1971 if (IS_STR_FILLED(info->version))
1973 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1975 if (IS_STR_FILLED(info->author))
1977 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1982 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
1984 g_RootMenu.ConsolePrint("%s", buffer);
1987 if (!m_FailList.empty())
1989 g_RootMenu.ConsolePrint("Load Errors:");
1991 SourceHook::List<CPlugin *>::iterator _iter;
1995 for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
1997 pl = (CPlugin *)*_iter;
1998 g_RootMenu.ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
2004 else if (strcmp(cmd, "load") == 0)
2008 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
2014 const char *filename = command.Arg(3);
2016 char pluginfile[256];
2017 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
2018 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
2020 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
2024 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
2030 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
2034 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
2039 else if (strcmp(cmd, "unload") == 0)
2043 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
2049 const char *arg = command.Arg(3);
2050 int id = strtol(arg, &end, 10);
2054 pl = GetPluginByOrder(id);
2057 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2063 char pluginfile[256];
2064 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2065 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2067 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2069 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2074 char name[PLATFORM_MAX_PATH];
2076 if (pl->GetStatus() < Plugin_Created)
2078 const sm_plugininfo_t *info = pl->GetPublicInfo();
2079 UTIL_Format(name, sizeof(name), (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2083 UTIL_Format(name, sizeof(name), "%s", pl->GetFilename());
2086 if (UnloadPlugin(pl))
2088 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
2092 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
2097 else if (strcmp(cmd, "unload_all") == 0)
2099 g_PluginSys.UnloadAll();
2100 g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
2103 else if (strcmp(cmd, "load_lock") == 0)
2105 if (m_LoadingLocked)
2107 g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
2111 m_LoadingLocked = true;
2112 g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
2116 else if (strcmp(cmd, "load_unlock") == 0)
2118 if (m_LoadingLocked)
2120 m_LoadingLocked = false;
2121 g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
2125 g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
2129 else if (strcmp(cmd, "info") == 0)
2133 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2139 const char *arg = command.Arg(3);
2140 int id = strtol(arg, &end, 10);
2144 pl = GetPluginByOrder(id);
2147 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2153 char pluginfile[256];
2154 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2155 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2157 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2159 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2164 const sm_plugininfo_t *info = pl->GetPublicInfo();
2166 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2167 if (pl->GetStatus() <= Plugin_Error)
2169 if (IS_STR_FILLED(info->name))
2171 if (IS_STR_FILLED(info->description))
2173 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2175 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2178 if (IS_STR_FILLED(info->author))
2180 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2182 if (IS_STR_FILLED(info->version))
2184 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2186 if (IS_STR_FILLED(info->url))
2188 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2190 if (pl->GetStatus() == Plugin_Error)
2192 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2196 if (pl->GetStatus() == Plugin_Running)
2198 g_RootMenu.ConsolePrint(" Status: running");
2202 g_RootMenu.ConsolePrint(" Status: not running");
2205 const char *typestr = "";
2206 switch (pl->GetType())
2208 case PluginType_MapUpdated:
2209 typestr = "Map Change if Updated";
2211 case PluginType_MapOnly:
2212 typestr = "Map Change";
2214 case PluginType_Private:
2215 case PluginType_Global:
2220 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2222 if (pl->m_FileVersion >= 3)
2224 g_RootMenu.ConsolePrint(" Timestamp: %s", pl->m_DateTime);
2229 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2230 if (pl->GetStatus() < Plugin_Created)
2232 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2233 info->name ? info->name : "<none>",
2234 info->version ? info->version : "<none>");
2235 if (IS_STR_FILLED(info->url))
2237 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2244 else if (strcmp(cmd, "refresh") == 0)
2246 g_SourceMod.DoGlobalPluginLoads();
2247 g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
2250 else if (strcmp(cmd, "reload") == 0)
2254 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
2260 const char *arg = command.Arg(3);
2261 int id = strtol(arg, &end, 10);
2265 pl = GetPluginByOrder(id);
2268 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2274 char pluginfile[256];
2275 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2276 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2278 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2280 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2285 char name[PLATFORM_MAX_PATH];
2286 const sm_plugininfo_t *info = pl->GetPublicInfo();
2287 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2289 if (ReloadPlugin(pl))
2291 g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
2295 g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
2302 /* Draw the main menu */
2303 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2304 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2305 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2306 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2307 g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
2308 g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
2309 g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
2310 g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
2311 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2312 g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
2315 bool CPluginManager::ReloadPlugin(CPlugin *pl)
2317 List<CPlugin *>::iterator iter;
2318 char filename[PLATFORM_MAX_PATH];
2324 strcpy(filename, pl->m_filename);
2325 ptype = pl->GetType();
2327 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
2335 if (!UnloadPlugin(pl))
2339 if (!(newpl=LoadPlugin(filename, true, ptype, NULL, 0, &wasloaded)))
2344 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2346 if ((*iter) == (CPlugin *)newpl)
2348 m_plugins.erase(iter);
2354 for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
2357 m_plugins.insert(iter, (CPlugin *)newpl);
2362 void CPluginManager::ReloadOrUnloadPlugins()
2364 /* If we're in a load lock, just skip this whole bit. */
2365 if (m_LoadingLocked)
2370 List<CPlugin *>::iterator iter;
2371 List<CPlugin *> tmp_list = m_plugins;
2375 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2378 if (pl->GetType() == PluginType_MapOnly)
2380 UnloadPlugin((IPlugin *)pl);
2382 else if (pl->GetType() == PluginType_MapUpdated)
2384 t = pl->GetFileTimeStamp();
2385 if (!t || t > pl->GetTimeStamp())
2387 pl->SetTimeStamp(t);
2388 UnloadPlugin((IPlugin *)pl);
2394 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2396 List<IPluginsListener *>::iterator iter;
2397 IPluginsListener *pListener;
2398 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2400 pListener = (*iter);
2401 pListener->OnPluginPauseChange(pl, paused);
2405 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2407 List<CPlugin *>::iterator iter;
2409 IPluginFunction *pFunction;
2411 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2415 if (pPlugin->GetStatus() <= Plugin_Paused)
2417 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2421 pForward->AddFunction(pFunction);
2427 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2429 if (pToken->type != g_PluginIdent)
2434 return (CPlugin *)(pToken->ptr);
2437 void CPluginManager::OnLibraryAction(const char *lib, bool is_a_plugin, bool drop)
2439 List<CPlugin *>::iterator iter;
2456 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2458 for (iter=m_plugins.begin();
2459 iter!=m_plugins.end();
2462 CPlugin *pl = (*iter);
2463 if (pl->GetStatus() != Plugin_Running)
2467 IPluginContext *pContext = pl->GetBaseContext();
2468 IPluginFunction *pf = pContext->GetFunctionByName(name);
2473 uint32_t num_vars = pContext->GetPubVarsNum();
2474 for (uint32_t i=0; i<num_vars; i++)
2476 sp_pubvar_t *pubvar;
2477 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2481 if (is_a_plugin && strncmp(pubvar->name, "__pl_", 5) == 0)
2483 plc = (_pl *)pubvar->offs;
2489 pContext->LocalToString(plc->name, &str);
2490 if (strcmp(str, lib) != 0)
2494 pf->PushString(lib);
2497 else if (!is_a_plugin && strncmp(pubvar->name, "__ext_", 6) == 0)
2499 ext = (_ext *)pubvar->offs;
2505 pContext->LocalToString(ext->name, &str);
2506 if (strcmp(str, lib) != 0)
2510 pf->PushString(lib);
2517 bool CPluginManager::LibraryExists(const char *lib)
2519 List<CPlugin *>::iterator iter;
2521 for (iter=m_plugins.begin();
2522 iter!=m_plugins.end();
2525 CPlugin *pl = (*iter);
2526 if (pl->GetStatus() != Plugin_Running)
2530 List<String>::iterator s_iter;
2531 for (s_iter = pl->m_Libraries.begin();
2532 s_iter != pl->m_Libraries.end();
2535 if ((*s_iter).compare(lib) == 0)
2545 void CPluginManager::AllPluginsLoaded()
2547 List<CPlugin *>::iterator iter;
2550 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2553 pl->Call_OnAllPluginsLoaded();
2557 void CPluginManager::UnloadAll()
2559 List<CPlugin *>::iterator iter;
2560 while ( (iter = m_plugins.begin()) != m_plugins.end() )
2562 UnloadPlugin((*iter));
2566 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
2569 List<CPlugin *>::iterator iter;
2571 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
2582 CPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
2588 id = strtol(arg, &end, 10);
2592 pl = GetPluginByOrder(id);
2600 char pluginfile[256];
2601 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2602 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2604 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2613 void CPluginManager::OnSourceModMaxPlayersChanged(int newvalue)
2615 SyncMaxClients(newvalue);
2618 void CPluginManager::SyncMaxClients(int max_clients)
2620 List<CPlugin *>::iterator iter;
2622 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2624 (*iter)->SyncMaxClients(max_clients);