Fixed double-period showing on native failures.
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();
78 sec.pOwner = g_PluginSys.GetIdentity();
79 sec.pIdentity = sec.pOwner;
81 g_HandleSys.FreeHandle(m_handle, &sec);
82 g_ShareSys.DestroyIdentity(m_ident);
85 if (m_pRuntime != NULL)
93 sm_trie_destroy(m_pProps);
95 for (size_t i=0; i<m_configs.size(); i++)
100 if (m_pPhrases != NULL)
102 m_pPhrases->Destroy();
107 void CPlugin::InitIdentity()
111 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
112 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
113 m_pRuntime->GetDefaultContext()->SetKey(1, m_ident);
114 m_pRuntime->GetDefaultContext()->SetKey(2, (IPlugin *)this);
118 unsigned int CPlugin::CalcMemUsage()
120 unsigned int base_size =
122 + sizeof(IdentityToken_t)
123 + (m_configs.size() * (sizeof(AutoConfig *) + sizeof(AutoConfig)))
124 + sm_trie_mem_usage(m_pProps);
126 for (unsigned int i = 0; i < m_configs.size(); i++)
128 base_size += m_configs[i]->autocfg.size();
129 base_size += m_configs[i]->folder.size();
132 for (List<String>::iterator i = m_Libraries.begin();
133 i != m_Libraries.end();
136 base_size += (*i).size();
139 for (List<String>::iterator i = m_RequiredLibs.begin();
140 i != m_RequiredLibs.end();
143 base_size += (*i).size();
149 Handle_t CPlugin::GetMyHandle()
154 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
156 char fullpath[PLATFORM_MAX_PATH];
157 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
158 FILE *fp = fopen(fullpath, "rb");
160 CPlugin *pPlugin = new CPlugin(file);
166 snprintf(error, maxlength, "Unable to open file");
168 pPlugin->m_status = Plugin_BadLoad;
175 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
177 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
179 if (exists && remove)
181 sm_trie_delete(m_pProps, prop);
187 bool CPlugin::SetProperty(const char *prop, void *ptr)
189 return sm_trie_insert(m_pProps, prop, ptr);
192 IPluginRuntime *CPlugin::GetRuntime()
197 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
199 PluginStatus old_status = m_status;
202 if (old_status == Plugin_Running)
204 /* Tell everyone we're now paused */
205 g_PluginSys._SetPauseState(this, true);
209 va_start(ap, error_fmt);
210 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
213 if (m_pRuntime != NULL)
215 m_pRuntime->SetPauseState(true);
219 void CPlugin::UpdateInfo()
221 /* Now grab the info */
223 IPluginContext *base = GetBaseContext();
224 int err = base->FindPubvarByName("myinfo", &idx);
226 memset(&m_info, 0, sizeof(m_info));
228 if (err == SP_ERROR_NONE)
230 struct sm_plugininfo_c_t
238 sm_plugininfo_c_t *cinfo;
241 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
242 base->LocalToString(cinfo->name, (char **)&m_info.name);
243 base->LocalToString(cinfo->description, (char **)&m_info.description);
244 base->LocalToString(cinfo->author, (char **)&m_info.author);
245 base->LocalToString(cinfo->url, (char **)&m_info.url);
246 base->LocalToString(cinfo->version, (char **)&m_info.version);
249 m_info.author = m_info.author ? m_info.author : "";
250 m_info.description = m_info.description ? m_info.description : "";
251 m_info.name = m_info.name ? m_info.name : "";
252 m_info.url = m_info.url ? m_info.url : "";
253 m_info.version = m_info.version ? m_info.version : "";
255 if ((err = base->FindPubvarByName("__version", &idx)) == SP_ERROR_NONE)
257 struct __version_info
264 __version_info *info;
266 const char *pDate, *pTime;
271 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&info);
272 m_FileVersion = info->version;
273 if (m_FileVersion >= 3)
275 base->LocalToString(info->date, (char **)&pDate);
276 base->LocalToString(info->time, (char **)&pTime);
277 UTIL_Format(m_DateTime, sizeof(m_DateTime), "%s %s", pDate, pTime);
286 void CPlugin::Call_OnPluginStart()
288 if (m_status != Plugin_Loaded)
293 m_status = Plugin_Running;
296 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginStart");
303 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
305 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
309 void CPlugin::Call_OnPluginEnd()
311 if (m_status > Plugin_Paused)
317 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginEnd");
323 pFunction->Execute(&result);
326 void CPlugin::Call_OnAllPluginsLoaded()
328 if (m_status > Plugin_Paused)
338 m_bGotAllLoaded = true;
341 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnAllPluginsLoaded");
342 if (pFunction != NULL)
344 pFunction->Execute(&result);
349 if ((pFunction = m_pRuntime->GetFunctionByName("OnMapStart")) != NULL)
351 pFunction->Execute(NULL);
355 if (SM_AreConfigsExecuted())
357 SM_ExecuteForPlugin(GetBaseContext());
361 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
363 if (m_status != Plugin_Created)
368 m_status = Plugin_Loaded;
372 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad");
379 pFunction->PushCell(m_handle);
380 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
381 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
382 pFunction->PushCell(maxlength);
383 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
388 if (!result || m_status != Plugin_Loaded)
396 void *CPlugin::GetPluginStructure()
401 IPluginContext *CPlugin::GetBaseContext()
403 if (m_pRuntime == NULL)
408 return m_pRuntime->GetDefaultContext();
411 sp_context_t *CPlugin::GetContext()
416 const char *CPlugin::GetFilename()
421 PluginType CPlugin::GetType()
426 const sm_plugininfo_t *CPlugin::GetPublicInfo()
431 unsigned int CPlugin::GetSerial()
436 PluginStatus CPlugin::GetStatus()
441 bool CPlugin::IsDebugging()
443 if (m_pRuntime == NULL)
448 return m_pRuntime->IsDebugging();
451 void CPlugin::LibraryActions(bool dropping)
453 List<String>::iterator iter;
454 for (iter = m_Libraries.begin();
455 iter != m_Libraries.end();
458 g_PluginSys.OnLibraryAction((*iter).c_str(), true, dropping);
462 bool CPlugin::SetPauseState(bool paused)
464 if (paused && GetStatus() != Plugin_Running)
467 } else if (!paused && GetStatus() != Plugin_Paused) {
473 LibraryActions(true);
476 IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginPauseChange");
480 pFunction->PushCell(paused ? 1 : 0);
481 pFunction->Execute(&result);
486 m_status = Plugin_Paused;
487 m_pRuntime->SetPauseState(true);
489 m_status = Plugin_Running;
490 m_pRuntime->SetPauseState(false);
493 g_PluginSys._SetPauseState(this, paused);
497 LibraryActions(false);
503 IdentityToken_t *CPlugin::GetIdentity()
508 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
516 snprintf(error, maxlength, "Plugin is not runnable.");
521 if (debug && IsDebugging())
525 snprintf(error, maxlength, "Plugin is already in debug mode.");
529 else if (!debug && !IsDebugging())
533 snprintf(error, maxlength, "Plugins is already in production mode.");
538 ICompilation *co = g_pSourcePawn2->StartCompilation();
540 if (!co->SetOption("debug", (debug) ? "1" : "0"))
544 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
549 if ((err = m_pRuntime->ApplyCompilationOptions(co)) != SP_ERROR_NONE)
553 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
563 bool CPlugin::IsRunnable()
565 return (m_status <= Plugin_Paused) ? true : false;
568 time_t CPlugin::GetFileTimeStamp()
570 char path[PLATFORM_MAX_PATH];
571 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
572 #ifdef PLATFORM_WINDOWS
574 if (_stat(path, &s) != 0)
575 #elif defined PLATFORM_POSIX
577 if (stat(path, &s) != 0)
588 time_t CPlugin::GetTimeStamp()
593 void CPlugin::SetTimeStamp(time_t t)
598 IPhraseCollection *CPlugin::GetPhrases()
603 void CPlugin::DependencyDropped(CPlugin *pOwner)
610 List<String>::iterator reqlib_iter;
611 List<String>::iterator lib_iter;
612 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
614 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
616 if ((*reqlib_iter) == (*lib_iter))
618 m_LibraryMissing = true;
623 List<NativeEntry *>::iterator iter;
624 NativeEntry *pNative;
627 unsigned int unbound = 0;
629 for (iter = pOwner->m_Natives.begin();
630 iter != pOwner->m_Natives.end();
634 /* Find this native! */
635 if (m_pRuntime->FindNativeByName(pNative->name, &idx) != SP_ERROR_NONE)
640 m_pRuntime->GetNativeByIndex(idx, &native);
642 native->status = SP_NATIVE_UNBOUND;
648 m_FakeNativesMissing = true;
651 /* :IDEA: in the future, add native trapping? */
652 if (m_FakeNativesMissing || m_LibraryMissing)
654 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
658 unsigned int CPlugin::GetConfigCount()
660 return (unsigned int)m_configs.size();
663 AutoConfig *CPlugin::GetConfig(unsigned int i)
665 if (i >= GetConfigCount())
673 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
675 /* Do a check for duplicates to prevent double-execution */
676 for (size_t i = 0; i < m_configs.size(); i++)
678 if (m_configs[i]->autocfg.compare(cfg) == 0
679 && m_configs[i]->folder.compare(folder) == 0
680 && m_configs[i]->create == autoCreate)
686 AutoConfig *c = new AutoConfig;
690 c->create = autoCreate;
692 m_configs.push_back(c);
695 void CPlugin::DropEverything()
698 List<CPlugin *>::iterator iter;
699 List<WeakNative>::iterator wk_iter;
701 /* Tell everyone that depends on us that we're about to drop */
702 for (iter = m_Dependents.begin();
703 iter != m_Dependents.end();
707 pOther->DependencyDropped(this);
710 /* Note: we don't care about things we depend on.
711 * The reason is that extensions have their own cleanup
712 * code for plugins. Although the "right" design would be
713 * to centralize that here, i'm omitting it for now. Thus,
714 * the code below to walk the plugins list will suffice.
717 /* Other plugins could be holding weak references that were
718 * added by us. We need to clean all of those up now.
720 for (iter = g_PluginSys.m_plugins.begin();
721 iter != g_PluginSys.m_plugins.end();
724 (*iter)->DropRefsTo(this);
727 /* Proceed with the rest of the necessities. */
728 CNativeOwner::DropEverything();
731 bool CPlugin::AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func)
735 if ((pEntry = g_ShareSys.AddFakeNative(pFunc, name, func)) == NULL)
740 m_Natives.push_back(pEntry);
749 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
755 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
760 bool CPluginManager::CPluginIterator::MorePlugins()
762 return (current != mylist->end());
765 void CPluginManager::CPluginIterator::NextPlugin()
770 void CPluginManager::CPluginIterator::Release()
772 g_PluginSys.ReleaseIterator(this);
775 CPluginManager::CPluginIterator::~CPluginIterator()
779 void CPluginManager::CPluginIterator::Reset()
781 current = mylist->begin();
788 CPluginManager::CPluginManager()
790 m_LoadLookup = sm_trie_create();
791 m_AllPluginsLoaded = false;
793 m_LoadingLocked = false;
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 snprintf(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 snprintf(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 snprintf(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)
1012 "Unable to load plugin (error %d: %s)",
1014 g_pSourcePawn2->GetErrorString(err));
1018 pPlugin->UpdateInfo();
1019 pPlugin->m_status = Plugin_Created;
1023 /* Get the status */
1024 if (pPlugin->GetStatus() == Plugin_Created)
1026 /* First native pass - add anything from Core */
1027 g_ShareSys.BindNativesToPlugin(pPlugin, true);
1028 pPlugin->InitIdentity();
1029 if (pPlugin->Call_AskPluginLoad(error, maxlength))
1031 /* Autoload any modules */
1032 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
1036 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1040 /* Save the time stamp */
1041 time_t t = pPlugin->GetFileTimeStamp();
1042 pPlugin->SetTimeStamp(t);
1049 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
1052 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
1058 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
1064 if (res == LoadRes_AlreadyLoaded)
1070 if (res == LoadRes_NeverLoad)
1072 if (m_LoadingLocked)
1074 UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect");
1078 UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
1085 /* Run second pass if we need to */
1086 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
1088 if (!RunSecondPass(pl, error, maxlength))
1093 pl->Call_OnAllPluginsLoaded();
1099 void CPluginManager::LoadAutoPlugin(const char *plugin)
1103 char error[255] = "Unknown error";
1105 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
1107 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
1108 pl->SetErrorState(Plugin_Failed, "%s", error);
1111 if (res == LoadRes_Successful)
1117 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1119 List<IPluginsListener *>::iterator iter;
1120 IPluginsListener *pListener;
1122 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1124 pListener = (*iter);
1125 pListener->OnPluginCreated(pPlugin);
1128 m_plugins.push_back(pPlugin);
1129 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1132 void CPluginManager::LoadAll_SecondPass()
1134 List<CPlugin *>::iterator iter;
1138 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1141 if (pPlugin->GetStatus() == Plugin_Loaded)
1144 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1146 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1147 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1152 m_AllPluginsLoaded = true;
1155 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1164 IPluginContext *pBase = pPlugin->GetBaseContext();
1165 uint32_t num = pBase->GetPubVarsNum();
1166 sp_pubvar_t *pubvar;
1168 char pathfile[PLATFORM_MAX_PATH];
1170 for (uint32_t i=0; i<num; i++)
1172 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1176 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1178 pl = (_pl *)pubvar->offs;
1179 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1183 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1187 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1188 if (strcmp(pathfile, file) == 0)
1192 if (pl->required == false)
1194 IPluginFunction *pFunc;
1196 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1197 if ((pFunc=pBase->GetFunctionByName(buffer)))
1200 pFunc->Execute(&res);
1201 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1205 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1213 /* Check that we aren't registering the same library twice */
1214 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1216 pPlugin->m_RequiredLibs.push_back(name);
1222 List<CPlugin *>::iterator iter;
1225 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1228 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1238 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1249 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1251 /* Find any extensions this plugin needs */
1260 IPluginContext *pBase = pPlugin->GetBaseContext();
1261 uint32_t num = pBase->GetPubVarsNum();
1262 sp_pubvar_t *pubvar;
1264 char path[PLATFORM_MAX_PATH];
1266 for (uint32_t i=0; i<num; i++)
1268 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1272 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1274 ext = (_ext *)pubvar->offs;
1275 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1279 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1285 /* Attempt to auto-load if necessary */
1288 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1289 g_Extensions.LoadAutoExtension(path);
1294 /* Is this required? */
1297 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1298 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1300 pExt = g_Extensions.FindExtensionByName(name);
1302 /* :TODO: should we bind to unloaded extensions?
1303 * Currently the extension manager will ignore this.
1305 if (!pExt || !pExt->IsRunning(NULL, 0))
1309 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1315 g_Extensions.BindChildPlugin(pExt, pPlugin);
1320 IPluginFunction *pFunc;
1322 UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
1324 if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
1327 pFunc->Execute(&res);
1328 if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
1332 UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
1345 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1347 /* Second pass for extension requirements */
1348 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1353 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1358 /* Run another binding pass */
1359 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1361 /* Find any unbound natives. Right now, these are not allowed. */
1362 IPluginContext *pContext = pPlugin->GetBaseContext();
1363 uint32_t num = pContext->GetNativesNum();
1364 sp_native_t *native;
1365 for (unsigned int i=0; i<num; i++)
1367 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1371 if (native->status == SP_NATIVE_UNBOUND
1372 && native->name[0] != '@'
1373 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1377 snprintf(error, maxlength, "Native \"%s\" was not found", native->name);
1383 /* Finish by telling all listeners */
1384 List<IPluginsListener *>::iterator iter;
1385 IPluginsListener *pListener;
1386 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1388 pListener = (*iter);
1389 pListener->OnPluginLoaded(pPlugin);
1392 /* Tell this plugin to finish initializing itself */
1393 pPlugin->Call_OnPluginStart();
1395 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1396 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_Natives.size())
1398 List<CPlugin *>::iterator pl_iter;
1400 for (pl_iter = m_plugins.begin();
1401 pl_iter != m_plugins.end();
1404 pOther = (*pl_iter);
1405 if ((pOther->GetStatus() == Plugin_Error
1406 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1407 || pOther->m_FakeNativesMissing)
1409 TryRefreshDependencies(pOther);
1411 else if ((pOther->GetStatus() == Plugin_Running
1412 || pOther->GetStatus() == Plugin_Paused)
1413 && pOther != pPlugin)
1415 List<NativeEntry *>::iterator nv_iter;
1416 for (nv_iter = pPlugin->m_Natives.begin();
1417 nv_iter != pPlugin->m_Natives.end();
1420 g_ShareSys.BindNativeToPlugin(pOther, (*nv_iter));
1426 /* Go through our libraries and tell other plugins they're added */
1427 List<String>::iterator s_iter;
1428 for (s_iter = pPlugin->m_Libraries.begin();
1429 s_iter != pPlugin->m_Libraries.end();
1432 OnLibraryAction((*s_iter).c_str(), true, false);
1435 /* :TODO: optimize? does this even matter? */
1436 pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
1441 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1443 assert(pPlugin->GetBaseContext() != NULL);
1445 g_ShareSys.BindNativesToPlugin(pPlugin, false);
1447 List<String>::iterator lib_iter;
1448 List<String>::iterator req_iter;
1449 List<CPlugin *>::iterator pl_iter;
1451 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1454 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1457 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1459 if ((*req_iter) == (*lib_iter))
1467 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1472 /* Find any unbound natives
1473 * Right now, these are not allowed
1475 IPluginContext *pContext = pPlugin->GetBaseContext();
1476 uint32_t num = pContext->GetNativesNum();
1477 sp_native_t *native;
1478 for (unsigned int i=0; i<num; i++)
1480 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1484 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1486 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1491 if (pPlugin->GetStatus() == Plugin_Error)
1493 /* If we got here, all natives are okay again! */
1494 pPlugin->m_status = Plugin_Running;
1495 if (pPlugin->m_pRuntime->IsPaused())
1497 pPlugin->m_pRuntime->SetPauseState(false);
1498 _SetPauseState(pPlugin, false);
1503 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1505 CPlugin *pPlugin = (CPlugin *)plugin;
1507 /* This prevents removal during insertion or anything else weird */
1508 if (m_plugins.find(pPlugin) == m_plugins.end())
1513 IPluginContext *pContext = plugin->GetBaseContext();
1514 if (pContext->IsInExec())
1517 UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
1518 engine->ServerCommand(buffer);
1522 /* Remove us from the lookup table and linked list */
1523 m_plugins.remove(pPlugin);
1524 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1526 /* Go through our libraries and tell other plugins they're gone */
1527 List<String>::iterator s_iter;
1528 for (s_iter = pPlugin->m_Libraries.begin();
1529 s_iter != pPlugin->m_Libraries.end();
1532 OnLibraryAction((*s_iter).c_str(), true, true);
1535 List<IPluginsListener *>::iterator iter;
1536 IPluginsListener *pListener;
1538 if (pPlugin->GetStatus() <= Plugin_Error)
1540 /* Notify listeners of unloading */
1541 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1543 pListener = (*iter);
1544 pListener->OnPluginUnloaded(pPlugin);
1547 pPlugin->Call_OnPluginEnd();
1550 pPlugin->DropEverything();
1552 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1554 /* Notify listeners of destruction */
1555 pListener = (*iter);
1556 pListener->OnPluginDestroyed(pPlugin);
1559 /* Tell the plugin to delete itself */
1565 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1568 IPluginContext *pContext;
1570 pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
1572 if (pContext->GetKey(2, (void **)&pPlugin))
1580 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
1582 return (CPlugin *)FindPluginByContext(ctx);
1585 unsigned int CPluginManager::GetPluginCount()
1587 return m_plugins.size();
1590 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1592 m_listeners.push_back(listener);
1595 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1597 m_listeners.remove(listener);
1600 IPluginIterator *CPluginManager::GetPluginIterator()
1602 if (m_iters.empty())
1604 return new CPluginIterator(&m_plugins);
1606 CPluginIterator *iter = m_iters.front();
1613 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1618 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1620 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1621 size_t alias_len = 0;
1622 size_t local_len = 0;
1624 const char *ptr = alias;
1625 unsigned int alias_explicit_paths = 0;
1626 unsigned int alias_path_end = 0;
1627 while (*ptr != '\0')
1629 if (*ptr == '\\' || *ptr == '/')
1631 alias_explicit_paths++;
1632 alias_path_end = alias_len;
1638 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1640 /* Trailing slash is totally invalid here */
1645 unsigned int local_explicit_paths = 0;
1646 unsigned int local_path_end = 0;
1647 while (*ptr != '\0')
1649 if (*ptr == '\\' || *ptr == '/')
1651 local_explicit_paths++;
1652 local_path_end = local_len;
1658 /* If the alias has more explicit paths than the real path,
1659 * no match will be possible.
1661 if (alias_explicit_paths > local_explicit_paths)
1666 if (alias_explicit_paths)
1668 /* We need to find if the paths match now. For example, these should all match:
1670 * csdm optional/csdm
1671 * csdm/ban optional/crab/csdm/ban
1673 const char *aliasptr = alias;
1674 const char *localptr = localpath;
1678 if (*aliasptr != *localptr)
1680 /* We have to knock one path off */
1681 local_explicit_paths--;
1682 if (alias_explicit_paths > local_explicit_paths)
1684 /* Skip out if we're gonna have an impossible match */
1687 /* Eat up localptr tokens until we get a result */
1688 while (((localptr - localpath) < (int)local_path_end)
1690 && *localptr != '\\')
1694 /* Check if we hit the end of our searchable area.
1695 * This probably isn't possible because of the path
1696 * count check, but it's a good idea anyway.
1698 if ((localptr - localpath) >= (int)local_path_end)
1702 /* Consume the slash token */
1705 /* Reset the alias pointer so we can continue consuming */
1711 * This is safe because if localptr terminates early, aliasptr will too
1715 /* We should never reach the end of the string because of this check. */
1716 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1717 bool localend = (localptr - localpath) > (int)local_path_end;
1718 if (aliasend || localend)
1720 if (aliasend && localend)
1722 /* we matched, and we can break out now */
1726 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1731 /* If we got here, it's safe to compare the next two tokens */
1732 if (*localptr != *aliasptr)
1743 /* If we got here, it's time to compare filenames */
1744 const char *aliasptr = alias;
1745 const char *localptr = localpath;
1747 if (alias_explicit_paths)
1749 aliasptr = &alias[alias_path_end + 1];
1752 if (local_explicit_paths)
1754 localptr = &localpath[local_path_end + 1];
1759 if (*aliasptr == '*')
1761 /* First, see if this is the last character */
1762 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1764 /* If so, there's no need to match anything else */
1767 /* Otherwise, we need to search for an appropriate matching sequence in local.
1768 * Note that we only need to search up to the next asterisk.
1772 const char *local_orig = localptr;
1776 while (*aliasptr != '\0' && *aliasptr != '*')
1778 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1779 if (*aliasptr != *localptr)
1789 /* If we didn't get a match, we need to advance the search stream.
1790 * This will let us skip tokens while still searching for another match.
1792 localptr = ++local_orig;
1793 /* Make sure we don't go out of bounds */
1794 if (*localptr == '\0')
1805 /* If we got a match, move on to the next token */
1808 } else if (*aliasptr == '\0') {
1809 if (*localptr == '\0'
1811 strcmp(localptr, ".smx") == 0)
1817 } else if (*aliasptr != *localptr) {
1827 bool CPluginManager::IsLateLoadTime() const
1829 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1832 void CPluginManager::OnSourceModAllInitialized()
1834 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1837 g_HandleSys.InitAccessDefaults(NULL, &sec);
1839 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1840 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1842 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1843 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1845 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1847 g_ShareSys.AddInterface(NULL, this);
1850 void CPluginManager::OnSourceModShutdown()
1852 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1856 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1857 g_ShareSys.DestroyIdentType(g_PluginIdent);
1858 g_ShareSys.DestroyIdentity(m_MyIdent);
1861 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1863 /* We don't care about the internal object, actually */
1866 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
1868 *pSize = ((CPlugin *)object)->CalcMemUsage();
1872 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1880 sec.pIdentity = m_MyIdent;
1882 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1895 CPlugin *CPluginManager::GetPluginByOrder(int num)
1897 if (num < 1 || num > (int)GetPluginCount())
1905 SourceHook::List<CPlugin *>::iterator iter;
1906 for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
1913 const char *CPluginManager::GetStatusText(PluginStatus st)
1917 case Plugin_Running:
1923 case Plugin_Uncompiled:
1924 return "Uncompiled";
1925 case Plugin_BadLoad:
1935 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
1937 int argcount = command.ArgC();
1940 const char *cmd = command.Arg(2);
1941 if (strcmp(cmd, "list") == 0)
1944 unsigned int id = 1;
1945 int plnum = GetPluginCount();
1949 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1954 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1958 SourceHook::List<CPlugin *>::iterator iter;
1959 SourceHook::List<CPlugin *> m_FailList;
1961 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
1964 assert(pl->GetStatus() != Plugin_Created);
1966 const sm_plugininfo_t *info = pl->GetPublicInfo();
1967 if (pl->GetStatus() != Plugin_Running)
1969 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1971 if (pl->GetStatus() <= Plugin_Error)
1973 /* Plugin has failed to load. */
1974 m_FailList.push_back(pl);
1979 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1981 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1982 if (IS_STR_FILLED(info->version))
1984 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1986 if (IS_STR_FILLED(info->author))
1988 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1990 g_RootMenu.ConsolePrint("%s", buffer);
1993 if (!m_FailList.empty())
1995 g_RootMenu.ConsolePrint("Load Errors:");
1997 SourceHook::List<CPlugin *>::iterator _iter;
2001 for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
2003 pl = (CPlugin *)*_iter;
2004 g_RootMenu.ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
2010 else if (strcmp(cmd, "load") == 0)
2014 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
2020 const char *filename = command.Arg(3);
2022 char pluginfile[256];
2023 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
2024 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
2026 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
2030 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
2036 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
2040 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
2045 else if (strcmp(cmd, "unload") == 0)
2049 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
2055 const char *arg = command.Arg(3);
2056 int id = strtol(arg, &end, 10);
2060 pl = GetPluginByOrder(id);
2063 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2069 char pluginfile[256];
2070 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2071 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2073 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2075 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2080 char name[PLATFORM_MAX_PATH];
2081 const sm_plugininfo_t *info = pl->GetPublicInfo();
2082 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2084 if (UnloadPlugin(pl))
2086 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
2090 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
2095 else if (strcmp(cmd, "unload_all") == 0)
2097 g_PluginSys.UnloadAll();
2098 g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
2101 else if (strcmp(cmd, "load_lock") == 0)
2103 if (m_LoadingLocked)
2105 g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
2109 m_LoadingLocked = true;
2110 g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
2114 else if (strcmp(cmd, "load_unlock") == 0)
2116 if (m_LoadingLocked)
2118 m_LoadingLocked = false;
2119 g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
2123 g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
2127 else if (strcmp(cmd, "info") == 0)
2131 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2137 const char *arg = command.Arg(3);
2138 int id = strtol(arg, &end, 10);
2142 pl = GetPluginByOrder(id);
2145 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2151 char pluginfile[256];
2152 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2153 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2155 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2157 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2162 const sm_plugininfo_t *info = pl->GetPublicInfo();
2164 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2165 if (pl->GetStatus() <= Plugin_Error)
2167 if (IS_STR_FILLED(info->name))
2169 if (IS_STR_FILLED(info->description))
2171 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2173 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2176 if (IS_STR_FILLED(info->author))
2178 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2180 if (IS_STR_FILLED(info->version))
2182 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2184 if (IS_STR_FILLED(info->url))
2186 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2188 if (pl->GetStatus() == Plugin_Error)
2190 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2194 if (pl->GetStatus() == Plugin_Running)
2196 if (pl->IsDebugging())
2198 g_RootMenu.ConsolePrint(" Status: running, debugging");
2202 g_RootMenu.ConsolePrint(" Status: running");
2207 g_RootMenu.ConsolePrint(" Status: not running");
2210 const char *typestr = "";
2211 switch (pl->GetType())
2213 case PluginType_MapUpdated:
2214 typestr = "Map Change if Updated";
2216 case PluginType_MapOnly:
2217 typestr = "Map Change";
2219 case PluginType_Private:
2220 case PluginType_Global:
2225 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2227 if (pl->m_FileVersion >= 3)
2229 g_RootMenu.ConsolePrint(" Timestamp: %s", pl->m_DateTime);
2234 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2235 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2236 info->name ? info->name : "<none>",
2237 info->version ? info->version : "<none>");
2238 if (IS_STR_FILLED(info->url))
2240 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2246 else if (strcmp(cmd, "debug") == 0)
2250 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
2256 const char *arg = command.Arg(3);
2257 int id = strtol(arg, &end, 10);
2261 pl = GetPluginByOrder(id);
2264 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2270 char pluginfile[256];
2271 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2272 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2274 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2276 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2282 const char *mode = command.Arg(4);
2283 if ((res=strcmp("on", mode)) && strcmp("off", mode))
2285 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
2299 if (debug && pl->IsDebugging())
2301 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
2304 else if (!debug && !pl->IsDebugging())
2306 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
2311 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
2313 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
2318 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
2319 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
2323 else if (strcmp(cmd, "refresh") == 0)
2325 g_SourceMod.DoGlobalPluginLoads();
2326 g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
2329 else if (strcmp(cmd, "reload") == 0)
2333 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
2339 const char *arg = command.Arg(3);
2340 int id = strtol(arg, &end, 10);
2344 pl = GetPluginByOrder(id);
2347 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2353 char pluginfile[256];
2354 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2355 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2357 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2359 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2364 char name[PLATFORM_MAX_PATH];
2365 const sm_plugininfo_t *info = pl->GetPublicInfo();
2366 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2368 if (ReloadPlugin(pl))
2370 g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
2374 g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
2381 /* Draw the main menu */
2382 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2383 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
2384 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2385 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2386 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2387 g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
2388 g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
2389 g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
2390 g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
2391 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2392 g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
2395 bool CPluginManager::ReloadPlugin(CPlugin *pl)
2397 List<CPlugin *>::iterator iter;
2398 char filename[PLATFORM_MAX_PATH];
2399 bool debug, wasloaded;
2404 strcpy(filename, pl->m_filename);
2405 debug = pl->IsDebugging();
2406 ptype = pl->GetType();
2408 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
2416 if (!UnloadPlugin(pl))
2420 if (!(newpl=LoadPlugin(filename, debug, ptype, NULL, 0, &wasloaded)))
2425 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2427 if ((*iter) == (CPlugin *)newpl)
2429 m_plugins.erase(iter);
2435 for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
2438 m_plugins.insert(iter, (CPlugin *)newpl);
2443 void CPluginManager::ReloadOrUnloadPlugins()
2445 /* If we're in a load lock, just skip this whole bit. */
2446 if (m_LoadingLocked)
2451 List<CPlugin *>::iterator iter;
2452 List<CPlugin *> tmp_list = m_plugins;
2456 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2459 if (pl->GetType() == PluginType_MapOnly)
2461 UnloadPlugin((IPlugin *)pl);
2463 else if (pl->GetType() == PluginType_MapUpdated)
2465 t = pl->GetFileTimeStamp();
2466 if (!t || t > pl->GetTimeStamp())
2468 pl->SetTimeStamp(t);
2469 UnloadPlugin((IPlugin *)pl);
2475 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2477 List<IPluginsListener *>::iterator iter;
2478 IPluginsListener *pListener;
2479 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2481 pListener = (*iter);
2482 pListener->OnPluginPauseChange(pl, paused);
2486 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2488 List<CPlugin *>::iterator iter;
2490 IPluginFunction *pFunction;
2492 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2496 if (pPlugin->GetStatus() <= Plugin_Paused)
2498 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2502 pForward->AddFunction(pFunction);
2508 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2510 if (pToken->type != g_PluginIdent)
2515 return (CPlugin *)(pToken->ptr);
2518 void CPluginManager::OnLibraryAction(const char *lib, bool is_a_plugin, bool drop)
2520 List<CPlugin *>::iterator iter;
2537 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2539 for (iter=m_plugins.begin();
2540 iter!=m_plugins.end();
2543 CPlugin *pl = (*iter);
2544 if (pl->GetStatus() != Plugin_Running)
2548 IPluginContext *pContext = pl->GetBaseContext();
2549 IPluginFunction *pf = pContext->GetFunctionByName(name);
2554 uint32_t num_vars = pContext->GetPubVarsNum();
2555 for (uint32_t i=0; i<num_vars; i++)
2557 sp_pubvar_t *pubvar;
2558 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2562 if (is_a_plugin && strncmp(pubvar->name, "__pl_", 5) == 0)
2564 plc = (_pl *)pubvar->offs;
2570 pContext->LocalToString(plc->name, &str);
2571 if (strcmp(str, lib) != 0)
2575 pf->PushString(lib);
2578 else if (!is_a_plugin && strncmp(pubvar->name, "__ext_", 6) == 0)
2580 ext = (_ext *)pubvar->offs;
2586 pContext->LocalToString(ext->name, &str);
2587 if (strcmp(str, lib) != 0)
2591 pf->PushString(lib);
2598 bool CPluginManager::LibraryExists(const char *lib)
2600 List<CPlugin *>::iterator iter;
2602 for (iter=m_plugins.begin();
2603 iter!=m_plugins.end();
2606 CPlugin *pl = (*iter);
2607 if (pl->GetStatus() != Plugin_Running)
2611 List<String>::iterator s_iter;
2612 for (s_iter = pl->m_Libraries.begin();
2613 s_iter != pl->m_Libraries.end();
2616 if ((*s_iter).compare(lib) == 0)
2626 void CPluginManager::AllPluginsLoaded()
2628 List<CPlugin *>::iterator iter;
2631 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2634 pl->Call_OnAllPluginsLoaded();
2638 void CPluginManager::UnloadAll()
2640 List<CPlugin *>::iterator iter;
2641 while ( (iter = m_plugins.begin()) != m_plugins.end() )
2643 UnloadPlugin((*iter));
2647 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
2650 List<CPlugin *>::iterator iter;
2652 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
2663 CPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
2669 id = strtol(arg, &end, 10);
2673 pl = GetPluginByOrder(id);
2681 char pluginfile[256];
2682 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2683 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2685 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))