3 * =============================================================================
5 * Copyright (C) 2004-2007 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;
77 sec.pOwner = g_PluginSys.GetIdentity();
78 sec.pIdentity = sec.pOwner;
80 g_HandleSys.FreeHandle(m_handle, &sec);
81 g_ShareSys.DestroyIdentity(m_ident);
91 m_ctx.vm->FreeContext(m_ctx.ctx);
96 m_ctx.vm->AbortCompilation(m_ctx.co);
102 g_pSourcePawn->FreeFromMemory(m_plugin);
107 sm_trie_destroy(m_pProps);
109 for (size_t i=0; i<m_configs.size(); i++)
116 void CPlugin::InitIdentity()
120 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
121 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
122 m_ctx.base->SetIdentity(m_ident);
126 Handle_t CPlugin::GetMyHandle()
131 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
133 char fullpath[PLATFORM_MAX_PATH];
134 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
135 FILE *fp = fopen(fullpath, "rb");
137 CPlugin *pPlugin = new CPlugin(file);
143 snprintf(error, maxlength, "Unable to open file");
145 pPlugin->m_status = Plugin_BadLoad;
150 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
156 snprintf(error, maxlength, "Error %d while parsing plugin", err);
158 pPlugin->m_status = Plugin_BadLoad;
164 pPlugin->m_plugin = pl;
169 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
171 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
173 if (exists && remove)
175 sm_trie_delete(m_pProps, prop);
181 bool CPlugin::SetProperty(const char *prop, void *ptr)
183 return sm_trie_insert(m_pProps, prop, ptr);
186 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
193 /* :NOTICE: We will eventually need to change these natives
194 * for swapping in new contexts
196 if (m_ctx.co || m_ctx.ctx)
201 m_status = Plugin_Uncompiled;
204 m_ctx.co = vm->StartCompilation(m_plugin);
209 void CPlugin::CancelMyCompile()
216 m_ctx.vm->AbortCompilation(m_ctx.co);
221 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
229 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
232 memset(&m_ctx, 0, sizeof(m_ctx));
235 snprintf(error, maxlength, "JIT failed to compile (error %d)", err);
240 m_ctx.base = new BaseContext(m_ctx.ctx);
241 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
243 m_status = Plugin_Created;
251 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
253 PluginStatus old_status = m_status;
256 if (old_status == Plugin_Running)
258 /* Tell everyone we're now paused */
259 g_PluginSys._SetPauseState(this, true);
263 va_start(ap, error_fmt);
264 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
269 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
273 void CPlugin::UpdateInfo()
275 /* Now grab the info */
277 IPluginContext *base = GetBaseContext();
278 int err = base->FindPubvarByName("myinfo", &idx);
280 memset(&m_info, 0, sizeof(m_info));
282 if (err == SP_ERROR_NONE)
284 struct sm_plugininfo_c_t
292 sm_plugininfo_c_t *cinfo;
295 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
296 base->LocalToString(cinfo->name, (char **)&m_info.name);
297 base->LocalToString(cinfo->description, (char **)&m_info.description);
298 base->LocalToString(cinfo->author, (char **)&m_info.author);
299 base->LocalToString(cinfo->url, (char **)&m_info.url);
300 base->LocalToString(cinfo->version, (char **)&m_info.version);
303 m_info.author = m_info.author ? m_info.author : "";
304 m_info.description = m_info.description ? m_info.description : "";
305 m_info.name = m_info.name ? m_info.name : "";
306 m_info.url = m_info.url ? m_info.url : "";
307 m_info.version = m_info.version ? m_info.version : "";
310 void CPlugin::Call_OnPluginStart()
312 if (m_status != Plugin_Loaded)
317 m_status = Plugin_Running;
320 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
327 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
329 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
333 void CPlugin::Call_OnPluginEnd()
335 if (m_status > Plugin_Paused)
341 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
347 pFunction->Execute(&result);
350 void CPlugin::Call_OnAllPluginsLoaded()
352 if (m_status > Plugin_Paused)
362 m_bGotAllLoaded = true;
365 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnAllPluginsLoaded");
366 if (pFunction != NULL)
368 pFunction->Execute(&result);
373 if ((pFunction = m_ctx.base->GetFunctionByName("OnMapStart")) != NULL)
375 pFunction->Execute(NULL);
379 if (SM_AreConfigsExecuted())
381 SM_ExecuteForPlugin(GetBaseContext());
385 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
387 if (m_status != Plugin_Created)
392 m_status = Plugin_Loaded;
396 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
403 pFunction->PushCell(m_handle);
404 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
405 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
406 pFunction->PushCell(maxlength);
407 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
412 if (!result || m_status != Plugin_Loaded)
420 const sp_plugin_t *CPlugin::GetPluginStructure()
425 IPluginContext *CPlugin::GetBaseContext()
430 sp_context_t *CPlugin::GetContext()
435 const char *CPlugin::GetFilename()
440 PluginType CPlugin::GetType()
445 const sm_plugininfo_t *CPlugin::GetPublicInfo()
450 unsigned int CPlugin::GetSerial()
455 PluginStatus CPlugin::GetStatus()
460 bool CPlugin::IsDebugging()
467 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
470 void CPlugin::LibraryActions(bool dropping)
472 List<String>::iterator iter;
473 for (iter = m_Libraries.begin();
474 iter != m_Libraries.end();
477 g_PluginSys.OnLibraryAction((*iter).c_str(), true, dropping);
481 bool CPlugin::SetPauseState(bool paused)
483 if (paused && GetStatus() != Plugin_Running)
486 } else if (!paused && GetStatus() != Plugin_Paused) {
492 LibraryActions(true);
495 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
499 pFunction->PushCell(paused ? 1 : 0);
500 pFunction->Execute(&result);
505 m_status = Plugin_Paused;
506 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
508 m_status = Plugin_Running;
509 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
512 g_PluginSys._SetPauseState(this, paused);
516 LibraryActions(false);
522 IdentityToken_t *CPlugin::GetIdentity()
527 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
535 snprintf(error, maxlength, "Plugin is not runnable.");
540 if (debug && IsDebugging())
544 snprintf(error, maxlength, "Plugin is already in debug mode.");
548 else if (!debug && !IsDebugging())
552 snprintf(error, maxlength, "Plugins is already in production mode.");
557 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
558 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
562 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
567 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
571 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
572 new_ctx->hp = m_ctx.ctx->hp;
573 new_ctx->sp = m_ctx.ctx->sp;
574 new_ctx->frm = m_ctx.ctx->frm;
575 new_ctx->dbreak = m_ctx.ctx->dbreak;
576 new_ctx->context = m_ctx.ctx->context;
577 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
579 uint32_t nativeCount = m_plugin->info.natives_num;
580 for (uint32_t i=0; i<nativeCount; i++)
582 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
583 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
586 g_pVM->FreeContext(m_ctx.ctx);
588 m_ctx.base->SetContext(new_ctx);
596 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
604 bool CPlugin::IsRunnable()
606 return (m_status <= Plugin_Paused) ? true : false;
609 time_t CPlugin::GetFileTimeStamp()
611 char path[PLATFORM_MAX_PATH];
612 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
613 #ifdef PLATFORM_WINDOWS
615 if (_stat(path, &s) != 0)
616 #elif defined PLATFORM_POSIX
618 if (stat(path, &s) != 0)
629 time_t CPlugin::GetTimeStamp()
634 void CPlugin::SetTimeStamp(time_t t)
639 void CPlugin::AddLangFile(unsigned int index)
641 m_PhraseFiles.push_back(index);
644 size_t CPlugin::GetLangFileCount()
646 return m_PhraseFiles.size();
649 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
651 return m_PhraseFiles.at(index);
654 void CPlugin::DependencyDropped(CPlugin *pOwner)
661 List<String>::iterator reqlib_iter;
662 List<String>::iterator lib_iter;
663 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
665 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
667 if ((*reqlib_iter) == (*lib_iter))
669 m_LibraryMissing = true;
674 List<FakeNative *>::iterator iter;
678 unsigned int unbound = 0;
680 for (iter = pOwner->m_fakeNatives.begin();
681 iter != pOwner->m_fakeNatives.end();
685 /* Find this native! */
686 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
691 m_ctx.base->GetNativeByIndex(idx, &native);
693 native->status = SP_NATIVE_UNBOUND;
699 m_FakeNativesMissing = true;
702 /* :IDEA: in the future, add native trapping? */
703 if (m_FakeNativesMissing || m_LibraryMissing)
705 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
708 m_dependsOn.remove(pOwner);
711 unsigned int CPlugin::GetConfigCount()
713 return (unsigned int)m_configs.size();
716 AutoConfig *CPlugin::GetConfig(unsigned int i)
718 if (i >= GetConfigCount())
726 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
728 AutoConfig *c = new AutoConfig;
732 c->create = autoCreate;
734 m_configs.push_back(c);
741 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
747 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
752 bool CPluginManager::CPluginIterator::MorePlugins()
754 return (current != mylist->end());
757 void CPluginManager::CPluginIterator::NextPlugin()
762 void CPluginManager::CPluginIterator::Release()
764 g_PluginSys.ReleaseIterator(this);
767 CPluginManager::CPluginIterator::~CPluginIterator()
771 void CPluginManager::CPluginIterator::Reset()
773 current = mylist->begin();
780 CPluginManager::CPluginManager()
782 m_LoadLookup = sm_trie_create();
783 m_AllPluginsLoaded = false;
785 m_pNativeLookup = sm_trie_create();
786 m_pCoreNatives = sm_trie_create();
787 m_LoadingLocked = false;
790 CPluginManager::~CPluginManager()
793 * Ignore the fact that there might be plugins in the cache.
794 * This usually means that Core is not being unloaded properly, and everything
795 * will crash anyway. YAY
797 sm_trie_destroy(m_LoadLookup);
798 sm_trie_destroy(m_pNativeLookup);
799 sm_trie_destroy(m_pCoreNatives);
801 CStack<CPluginManager::CPluginIterator *>::iterator iter;
802 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
809 void CPluginManager::Shutdown()
811 List<CPlugin *>::iterator iter;
813 while ((iter = m_plugins.begin()) != m_plugins.end())
819 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
821 /* First read in the database of plugin settings */
823 unsigned int line, col;
824 m_AllPluginsLoaded = false;
825 if ((err=textparsers->ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
827 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
828 const char *err_msg = textparsers->GetSMCErrorString(err);
831 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
835 LoadPluginsFromDir(basedir, NULL);
838 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
840 char base_path[PLATFORM_MAX_PATH];
842 /* Form the current path to start reading from */
843 if (localpath == NULL)
845 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
847 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
850 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
855 g_LibSys.GetPlatformError(error, sizeof(error));
856 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
857 g_Logger.LogError("[SM] Platform returned error: %s", error);
861 while (dir->MoreFiles())
863 if (dir->IsEntryDirectory()
864 && (strcmp(dir->GetEntryName(), ".") != 0)
865 && (strcmp(dir->GetEntryName(), "..") != 0)
866 && (strcmp(dir->GetEntryName(), "disabled") != 0)
867 && (strcmp(dir->GetEntryName(), "optional") != 0))
869 char new_local[PLATFORM_MAX_PATH];
870 if (localpath == NULL)
872 /* If no path yet, don't add a former slash */
873 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
875 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
877 LoadPluginsFromDir(basedir, new_local);
878 } else if (dir->IsEntryFile()) {
879 const char *name = dir->GetEntryName();
880 size_t len = strlen(name);
882 && strcmp(&name[len-4], ".smx") == 0)
884 /* If the filename matches, load the plugin */
885 char plugin[PLATFORM_MAX_PATH];
886 if (localpath == NULL)
888 snprintf(plugin, sizeof(plugin), "%s", name);
890 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
892 LoadAutoPlugin(plugin);
897 g_LibSys.CloseDirectory(dir);
900 //well i have discovered that gabe newell is very fat, so i wrote this comment now
901 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
905 return LoadRes_NeverLoad;
908 bool no_load = false;
909 PluginSettings *pset;
910 unsigned int setcount = m_PluginInfo.GetSettingsNum();
911 for (unsigned int i=0; i<setcount; i++)
913 if ((pset = m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
917 if (pset->blockload_val)
925 * Does this plugin already exist?
928 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
930 /* Check to see if we should try reloading it */
931 if (pPlugin->GetStatus() == Plugin_BadLoad
932 || pPlugin->GetStatus() == Plugin_Error
933 || pPlugin->GetStatus() == Plugin_Failed
936 UnloadPlugin(pPlugin);
944 return LoadRes_AlreadyLoaded;
950 return LoadRes_NeverLoad;
953 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
955 assert(pPlugin != NULL);
957 pPlugin->m_type = PluginType_MapUpdated;
959 ICompilation *co = NULL;
961 if (pPlugin->m_status == Plugin_Uncompiled)
963 co = pPlugin->StartMyCompile(g_pVM);
966 for (unsigned int i=0; i<setcount; i++)
968 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
972 pPlugin->m_type = pset->type_val;
975 for (unsigned int j=0; j<pset->opts_num; j++)
977 const char *key, *val;
978 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
983 if (!g_pVM->SetCompilationOption(co, key, val))
987 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
989 pPlugin->CancelMyCompile();
997 /* Do the actual compiling */
1000 pPlugin->FinishMyCompile(error, maxlength);
1004 /* Get the status */
1005 if (pPlugin->GetStatus() == Plugin_Created)
1007 AddCoreNativesToPlugin(pPlugin);
1008 pPlugin->InitIdentity();
1009 if (pPlugin->Call_AskPluginLoad(error, maxlength))
1011 /* Autoload any modules */
1012 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
1016 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1020 /* Save the time stamp */
1021 time_t t = pPlugin->GetFileTimeStamp();
1022 pPlugin->SetTimeStamp(t);
1029 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
1032 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
1038 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
1044 if (res == LoadRes_AlreadyLoaded)
1050 if (res == LoadRes_NeverLoad)
1052 if (m_LoadingLocked)
1054 UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect.");
1058 UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
1065 /* Run second pass if we need to */
1066 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
1068 if (!RunSecondPass(pl, error, maxlength))
1073 pl->Call_OnAllPluginsLoaded();
1079 void CPluginManager::LoadAutoPlugin(const char *plugin)
1083 char error[255] = "Unknown error";
1085 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
1087 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
1088 pl->SetErrorState(Plugin_Failed, "%s", error);
1091 if (res == LoadRes_Successful)
1097 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1099 List<IPluginsListener *>::iterator iter;
1100 IPluginsListener *pListener;
1102 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1104 pListener = (*iter);
1105 pListener->OnPluginCreated(pPlugin);
1108 m_plugins.push_back(pPlugin);
1109 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1112 void CPluginManager::LoadAll_SecondPass()
1114 List<CPlugin *>::iterator iter;
1118 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1121 if (pPlugin->GetStatus() == Plugin_Loaded)
1124 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1126 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1127 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1132 m_AllPluginsLoaded = true;
1135 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1144 IPluginContext *pBase = pPlugin->GetBaseContext();
1145 uint32_t num = pBase->GetPubVarsNum();
1146 sp_pubvar_t *pubvar;
1148 char pathfile[PLATFORM_MAX_PATH];
1150 for (uint32_t i=0; i<num; i++)
1152 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1156 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1158 pl = (_pl *)pubvar->offs;
1159 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1163 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1167 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1168 if (strcmp(pathfile, file) == 0)
1172 if (pl->required == false)
1174 IPluginFunction *pFunc;
1176 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1177 if ((pFunc=pBase->GetFunctionByName(buffer)))
1180 pFunc->Execute(&res);
1181 if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
1185 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1193 /* Check that we aren't registering the same library twice */
1194 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1196 pPlugin->m_RequiredLibs.push_back(name);
1202 List<CPlugin *>::iterator iter;
1205 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1208 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1218 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1229 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1231 /* Find any extensions this plugin needs */
1240 IPluginContext *pBase = pPlugin->GetBaseContext();
1241 uint32_t num = pBase->GetPubVarsNum();
1242 sp_pubvar_t *pubvar;
1244 char path[PLATFORM_MAX_PATH];
1246 for (uint32_t i=0; i<num; i++)
1248 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1252 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1254 ext = (_ext *)pubvar->offs;
1255 if (!ext->required && !ext->autoload)
1259 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1263 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1269 /* Attempt to auto-load if necessary */
1272 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1273 g_Extensions.LoadAutoExtension(path);
1278 /* Is this required? */
1281 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1282 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1284 pExt = g_Extensions.FindExtensionByName(name);
1286 /* :TODO: should we bind to unloaded extensions?
1287 * Currently the extension manager will ignore this.
1289 if (!pExt || !pExt->IsRunning(NULL, 0))
1293 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1299 g_Extensions.BindChildPlugin(pExt, pPlugin);
1304 IPluginFunction *pFunc;
1306 UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
1308 if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
1311 pFunc->Execute(&res);
1312 if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
1316 UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
1329 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1331 /* Second pass for extension requirements */
1332 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1337 /* Bind all extra natives */
1338 g_Extensions.BindAllNativesToPlugin(pPlugin);
1340 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1345 AddFakeNativesToPlugin(pPlugin);
1347 /* Find any unbound natives
1348 * Right now, these are not allowed
1350 IPluginContext *pContext = pPlugin->GetBaseContext();
1351 uint32_t num = pContext->GetNativesNum();
1352 sp_native_t *native;
1353 for (unsigned int i=0; i<num; i++)
1355 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1359 if (native->status == SP_NATIVE_UNBOUND
1360 && native->name[0] != '@'
1361 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1365 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1371 /* Finish by telling all listeners */
1372 List<IPluginsListener *>::iterator iter;
1373 IPluginsListener *pListener;
1374 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1376 pListener = (*iter);
1377 pListener->OnPluginLoaded(pPlugin);
1380 /* Tell this plugin to finish initializing itself */
1381 pPlugin->Call_OnPluginStart();
1383 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1384 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_fakeNatives.size())
1386 List<CPlugin *>::iterator pl_iter;
1388 for (pl_iter = m_plugins.begin();
1389 pl_iter != m_plugins.end();
1392 pOther = (*pl_iter);
1393 if ((pOther->GetStatus() == Plugin_Error
1394 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1395 || pOther->m_FakeNativesMissing)
1397 TryRefreshDependencies(pOther);
1402 /* Go through our libraries and tell other plugins they're added */
1403 List<String>::iterator s_iter;
1404 for (s_iter = pPlugin->m_Libraries.begin();
1405 s_iter != pPlugin->m_Libraries.end();
1408 OnLibraryAction((*s_iter).c_str(), true, false);
1411 /* Finally, add the core language file */
1412 pPlugin->AddLangFile(g_pCorePhraseID);
1417 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1419 IPluginContext *pContext = pPlugin->GetBaseContext();
1422 uint32_t natives = pContext->GetNativesNum();
1423 sp_native_t *native;
1424 SPVM_NATIVE_FUNC pfn;
1425 for (uint32_t i=0; i<natives; i++)
1427 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1431 if (native->status == SP_NATIVE_BOUND)
1435 if (!sm_trie_retrieve(m_pCoreNatives, native->name, (void **)&pfn))
1439 pContext->BindNativeToIndex(i, pfn);
1443 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1445 assert(pPlugin->GetBaseContext() != NULL);
1447 AddFakeNativesToPlugin(pPlugin);
1449 List<String>::iterator lib_iter;
1450 List<String>::iterator req_iter;
1451 List<CPlugin *>::iterator pl_iter;
1453 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1456 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1459 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1461 if ((*req_iter) == (*lib_iter))
1469 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1474 /* Find any unbound natives
1475 * Right now, these are not allowed
1477 IPluginContext *pContext = pPlugin->GetBaseContext();
1478 uint32_t num = pContext->GetNativesNum();
1479 sp_native_t *native;
1480 for (unsigned int i=0; i<num; i++)
1482 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1486 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1488 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1493 if (pPlugin->GetStatus() == Plugin_Error)
1495 /* If we got here, all natives are okay again! */
1496 pPlugin->m_status = Plugin_Running;
1497 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1499 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1500 _SetPauseState(pPlugin, false);
1505 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1507 IPluginContext *pContext = pPlugin->GetBaseContext();
1508 sp_nativeinfo_t native;
1510 List<FakeNative *>::iterator iter;
1511 FakeNative *pNative;
1513 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1516 ctx = pNative->ctx->GetContext();
1517 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1519 /* Ignore natives in paused plugins */
1522 native.name = pNative->name.c_str();
1523 native.func = pNative->func;
1524 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1527 pContext->FindNativeByName(native.name, &idx);
1528 if (pPlugin->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL)
1530 WeakNative wkn(pPlugin, idx);
1531 GetPluginByCtx(ctx)->m_WeakNatives.push_back(wkn);
1534 /* Add us as a dependency, but we're careful not to do this circularly! */
1535 if (pNative->ctx != pContext)
1537 CPlugin *pOther = GetPluginByCtx(ctx);
1538 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1540 pOther->m_dependents.push_back(pPlugin);
1542 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1544 pPlugin->m_dependsOn.push_back(pOther);
1551 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1553 CPlugin *pPlugin = (CPlugin *)plugin;
1555 /* This prevents removal during insertion or anything else weird */
1556 if (m_plugins.find(pPlugin) == m_plugins.end())
1561 IPluginContext *pContext = plugin->GetBaseContext();
1562 if (pContext->IsInExec())
1565 UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
1566 engine->ServerCommand(buffer);
1570 /* Remove us from the lookup table and linked list */
1571 m_plugins.remove(pPlugin);
1572 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1574 /* Go through our libraries and tell other plugins they're gone */
1575 List<String>::iterator s_iter;
1576 for (s_iter = pPlugin->m_Libraries.begin();
1577 s_iter != pPlugin->m_Libraries.end();
1580 OnLibraryAction((*s_iter).c_str(), true, true);
1583 /* Go through all dependent plugins and tell them this plugin is now gone */
1584 List<CPlugin *>::iterator pl_iter;
1586 for (pl_iter = pPlugin->m_dependents.begin();
1587 pl_iter != pPlugin->m_dependents.end();
1590 pOther = (*pl_iter);
1591 pOther->DependencyDropped(pPlugin);
1594 /* Tell everyone we depend on that we no longer exist */
1595 for (pl_iter = pPlugin->m_dependsOn.begin();
1596 pl_iter != pPlugin->m_dependsOn.end();
1599 pOther = (*pl_iter);
1600 pOther->m_dependents.remove(pPlugin);
1603 /* Remove weak references to us */
1604 for (pl_iter = m_plugins.begin();
1605 pl_iter != m_plugins.end();
1608 pOther = (*pl_iter);
1609 List<WeakNative>::iterator wk_iter = pOther->m_WeakNatives.begin();
1610 while (wk_iter != pOther->m_WeakNatives.end())
1612 if ((*wk_iter).pl == pPlugin)
1614 wk_iter = pOther->m_WeakNatives.erase(wk_iter);
1621 List<IPluginsListener *>::iterator iter;
1622 IPluginsListener *pListener;
1624 if (pPlugin->GetStatus() <= Plugin_Error)
1626 /* Notify listeners of unloading */
1627 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1629 pListener = (*iter);
1630 pListener->OnPluginUnloaded(pPlugin);
1633 pPlugin->Call_OnPluginEnd();
1636 /* Unbound weak natives */
1637 List<WeakNative>::iterator wk_iter;
1638 for (wk_iter=pPlugin->m_WeakNatives.begin(); wk_iter!=pPlugin->m_WeakNatives.end(); wk_iter++)
1640 WeakNative & wkn = (*wk_iter);
1641 sp_context_t *ctx = wkn.pl->GetContext();
1642 ctx->natives[wkn.idx].status = SP_NATIVE_UNBOUND;
1643 wkn.pl->m_FakeNativesMissing = true;
1646 /* Remove all of our native functions */
1647 List<FakeNative *>::iterator fn_iter;
1648 FakeNative *pNative;
1649 for (fn_iter = pPlugin->m_fakeNatives.begin();
1650 fn_iter != pPlugin->m_fakeNatives.end();
1653 pNative = (*fn_iter);
1654 m_Natives.remove(pNative);
1655 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1656 g_pVM->DestroyFakeNative(pNative->func);
1660 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1662 /* Notify listeners of destruction */
1663 pListener = (*iter);
1664 pListener->OnPluginDestroyed(pPlugin);
1667 /* Tell the plugin to delete itself */
1673 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1675 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1679 unsigned int CPluginManager::GetPluginCount()
1681 return m_plugins.size();
1684 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1686 m_listeners.push_back(listener);
1689 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1691 m_listeners.remove(listener);
1694 IPluginIterator *CPluginManager::GetPluginIterator()
1696 if (m_iters.empty())
1698 return new CPluginIterator(&m_plugins);
1700 CPluginIterator *iter = m_iters.front();
1707 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1712 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1714 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1715 size_t alias_len = 0;
1716 size_t local_len = 0;
1718 const char *ptr = alias;
1719 unsigned int alias_explicit_paths = 0;
1720 unsigned int alias_path_end = 0;
1721 while (*ptr != '\0')
1723 if (*ptr == '\\' || *ptr == '/')
1725 alias_explicit_paths++;
1726 alias_path_end = alias_len;
1732 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1734 /* Trailing slash is totally invalid here */
1739 unsigned int local_explicit_paths = 0;
1740 unsigned int local_path_end = 0;
1741 while (*ptr != '\0')
1743 if (*ptr == '\\' || *ptr == '/')
1745 local_explicit_paths++;
1746 local_path_end = local_len;
1752 /* If the alias has more explicit paths than the real path,
1753 * no match will be possible.
1755 if (alias_explicit_paths > local_explicit_paths)
1760 if (alias_explicit_paths)
1762 /* We need to find if the paths match now. For example, these should all match:
1764 * csdm optional/csdm
1765 * csdm/ban optional/crab/csdm/ban
1767 const char *aliasptr = alias;
1768 const char *localptr = localpath;
1772 if (*aliasptr != *localptr)
1774 /* We have to knock one path off */
1775 local_explicit_paths--;
1776 if (alias_explicit_paths > local_explicit_paths)
1778 /* Skip out if we're gonna have an impossible match */
1781 /* Eat up localptr tokens until we get a result */
1782 while (((localptr - localpath) < (int)local_path_end)
1784 && *localptr != '\\')
1788 /* Check if we hit the end of our searchable area.
1789 * This probably isn't possible because of the path
1790 * count check, but it's a good idea anyway.
1792 if ((localptr - localpath) >= (int)local_path_end)
1796 /* Consume the slash token */
1799 /* Reset the alias pointer so we can continue consuming */
1805 * This is safe because if localptr terminates early, aliasptr will too
1809 /* We should never reach the end of the string because of this check. */
1810 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1811 bool localend = (localptr - localpath) > (int)local_path_end;
1812 if (aliasend || localend)
1814 if (aliasend && localend)
1816 /* we matched, and we can break out now */
1820 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1825 /* If we got here, it's safe to compare the next two tokens */
1826 if (*localptr != *aliasptr)
1837 /* If we got here, it's time to compare filenames */
1838 const char *aliasptr = alias;
1839 const char *localptr = localpath;
1841 if (alias_explicit_paths)
1843 aliasptr = &alias[alias_path_end + 1];
1846 if (local_explicit_paths)
1848 localptr = &localpath[local_path_end + 1];
1853 if (*aliasptr == '*')
1855 /* First, see if this is the last character */
1856 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1858 /* If so, there's no need to match anything else */
1861 /* Otherwise, we need to search for an appropriate matching sequence in local.
1862 * Note that we only need to search up to the next asterisk.
1866 const char *local_orig = localptr;
1870 while (*aliasptr != '\0' && *aliasptr != '*')
1872 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1873 if (*aliasptr != *localptr)
1883 /* If we didn't get a match, we need to advance the search stream.
1884 * This will let us skip tokens while still searching for another match.
1886 localptr = ++local_orig;
1887 /* Make sure we don't go out of bounds */
1888 if (*localptr == '\0')
1899 /* If we got a match, move on to the next token */
1902 } else if (*aliasptr == '\0') {
1903 if (*localptr == '\0'
1905 strcmp(localptr, ".smx") == 0)
1911 } else if (*aliasptr != *localptr) {
1921 bool CPluginManager::IsLateLoadTime() const
1923 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1926 void CPluginManager::OnSourceModAllInitialized()
1928 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1931 g_HandleSys.InitAccessDefaults(NULL, &sec);
1933 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1934 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1936 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1937 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1939 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1941 g_ShareSys.AddInterface(NULL, this);
1944 void CPluginManager::OnSourceModShutdown()
1946 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1950 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1951 g_ShareSys.DestroyIdentType(g_PluginIdent);
1952 g_ShareSys.DestroyIdentity(m_MyIdent);
1955 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1957 /* We don't care about the internal object, actually */
1960 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1962 for (unsigned int i = 0; natives[i].func != NULL; i++)
1964 sm_trie_insert(m_pCoreNatives, natives[i].name, (void *)natives[i].func);
1968 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1976 sec.pIdentity = m_MyIdent;
1978 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1991 CPlugin *CPluginManager::GetPluginByOrder(int num)
1993 if (num < 1 || num > (int)GetPluginCount())
2001 IPluginIterator *iter = GetPluginIterator();
2002 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
2004 pl = (CPlugin *)(iter->GetPlugin());
2010 const char *CPluginManager::GetStatusText(PluginStatus st)
2014 case Plugin_Running:
2020 case Plugin_Uncompiled:
2021 return "Uncompiled";
2022 case Plugin_BadLoad:
2032 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
2034 int argcount = command.ArgC();
2037 const char *cmd = command.Arg(2);
2038 if (strcmp(cmd, "list") == 0)
2041 unsigned int id = 1;
2042 int plnum = GetPluginCount();
2046 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
2051 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
2054 IPluginIterator *iter = GetPluginIterator();
2055 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
2057 IPlugin *pl = iter->GetPlugin();
2058 assert(pl->GetStatus() != Plugin_Created);
2060 const sm_plugininfo_t *info = pl->GetPublicInfo();
2061 if (pl->GetStatus() != Plugin_Running)
2063 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
2067 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
2069 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2070 if (IS_STR_FILLED(info->version))
2072 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
2074 if (IS_STR_FILLED(info->author))
2076 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
2078 g_RootMenu.ConsolePrint("%s", buffer);
2084 else if (strcmp(cmd, "load") == 0)
2088 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
2094 const char *filename = command.Arg(3);
2096 char pluginfile[256];
2097 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
2098 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
2100 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
2104 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
2110 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
2114 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
2119 else if (strcmp(cmd, "unload") == 0)
2123 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
2129 const char *arg = command.Arg(3);
2130 int id = strtol(arg, &end, 10);
2134 pl = GetPluginByOrder(id);
2137 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2143 char pluginfile[256];
2144 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2145 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2147 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2149 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2154 char name[PLATFORM_MAX_PATH];
2155 const sm_plugininfo_t *info = pl->GetPublicInfo();
2156 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2158 if (UnloadPlugin(pl))
2160 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
2164 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
2169 else if (strcmp(cmd, "unload_all") == 0)
2171 g_PluginSys.UnloadAll();
2172 g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
2175 else if (strcmp(cmd, "load_lock") == 0)
2177 if (m_LoadingLocked)
2179 g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
2183 m_LoadingLocked = true;
2184 g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
2188 else if (strcmp(cmd, "load_unlock") == 0)
2190 if (m_LoadingLocked)
2192 m_LoadingLocked = false;
2193 g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
2197 g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
2201 else if (strcmp(cmd, "info") == 0)
2205 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2209 int num = atoi(command.Arg(3));
2210 if (num < 1 || num > (int)GetPluginCount())
2212 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
2216 CPlugin *pl = GetPluginByOrder(num);
2217 const sm_plugininfo_t *info = pl->GetPublicInfo();
2219 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2220 if (pl->GetStatus() <= Plugin_Error)
2222 if (IS_STR_FILLED(info->name))
2224 if (IS_STR_FILLED(info->description))
2226 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2228 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2231 if (IS_STR_FILLED(info->author))
2233 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2235 if (IS_STR_FILLED(info->version))
2237 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2239 if (IS_STR_FILLED(info->url))
2241 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2243 if (pl->GetStatus() == Plugin_Error)
2245 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2249 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
2250 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
2252 const char *typestr = "";
2253 switch (pl->GetType())
2255 case PluginType_MapUpdated:
2256 typestr = "Map Change if Updated";
2258 case PluginType_MapOnly:
2259 typestr = "Map Change";
2261 case PluginType_Private:
2262 case PluginType_Global:
2267 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2272 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2273 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2274 info->name ? info->name : "<none>",
2275 info->version ? info->version : "<none>");
2276 if (IS_STR_FILLED(info->url))
2278 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2284 else if (strcmp(cmd, "debug") == 0)
2288 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
2292 int num = atoi(command.Arg(3));
2293 if (num < 1 || num > (int)GetPluginCount())
2295 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
2300 const char *mode = command.Arg(4);
2301 if ((res=strcmp("on", mode)) && strcmp("off", mode))
2303 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
2317 CPlugin *pl = GetPluginByOrder(num);
2318 if (debug && pl->IsDebugging())
2320 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
2323 else if (!debug && !pl->IsDebugging())
2325 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
2330 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
2332 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
2337 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
2338 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
2342 else if (strcmp(cmd, "refresh") == 0)
2344 g_SourceMod.DoGlobalPluginLoads();
2345 g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
2348 else if (strcmp(cmd, "reload") == 0)
2352 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
2358 const char *arg = command.Arg(3);
2359 int id = strtol(arg, &end, 10);
2363 pl = GetPluginByOrder(id);
2366 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2372 char pluginfile[256];
2373 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2374 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2376 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2378 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2383 char name[PLATFORM_MAX_PATH];
2384 const sm_plugininfo_t *info = pl->GetPublicInfo();
2385 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2387 if (ReloadPlugin(pl))
2389 g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
2393 g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
2400 /* Draw the main menu */
2401 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2402 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
2403 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2404 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2405 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2406 g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
2407 g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
2408 g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
2409 g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
2410 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2411 g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
2414 bool CPluginManager::ReloadPlugin(CPlugin *pl)
2416 List<CPlugin *>::iterator iter;
2417 char filename[PLATFORM_MAX_PATH];
2418 bool debug, wasloaded;
2423 strcpy(filename, pl->m_filename);
2424 debug = pl->IsDebugging();
2425 ptype = pl->GetType();
2427 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
2435 if (!UnloadPlugin(pl))
2439 if (!(newpl=LoadPlugin(filename, debug, ptype, NULL, 0, &wasloaded)))
2444 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2446 if ((*iter) == (CPlugin *)newpl)
2448 m_plugins.erase(iter);
2454 for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
2457 m_plugins.insert(iter, (CPlugin *)newpl);
2462 void CPluginManager::ReloadOrUnloadPlugins()
2464 /* If we're in a load lock, just skip this whole bit. */
2465 if (m_LoadingLocked)
2470 List<CPlugin *>::iterator iter;
2471 List<CPlugin *> tmp_list = m_plugins;
2475 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2478 if (pl->GetType() == PluginType_MapOnly)
2480 UnloadPlugin((IPlugin *)pl);
2482 else if (pl->GetType() == PluginType_MapUpdated)
2484 t = pl->GetFileTimeStamp();
2485 if (!t || t > pl->GetTimeStamp())
2487 pl->SetTimeStamp(t);
2488 UnloadPlugin((IPlugin *)pl);
2494 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2496 List<IPluginsListener *>::iterator iter;
2497 IPluginsListener *pListener;
2498 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2500 pListener = (*iter);
2501 pListener->OnPluginPauseChange(pl, paused);
2505 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
2507 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
2512 FakeNative *pNative = new FakeNative;
2514 pNative->func = g_pVM->CreateFakeNative(func, pNative);
2521 pNative->call = pFunction;
2522 pNative->name.assign(name);
2523 pNative->ctx = pFunction->GetParentContext();
2525 m_Natives.push_back(pNative);
2526 sm_trie_insert(m_pNativeLookup, name,pNative);
2528 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
2529 pPlugin->m_fakeNatives.push_back(pNative);
2534 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2536 List<CPlugin *>::iterator iter;
2538 IPluginFunction *pFunction;
2540 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2544 if (pPlugin->GetStatus() <= Plugin_Paused)
2546 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2550 pForward->AddFunction(pFunction);
2556 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2558 if (pToken->type != g_PluginIdent)
2563 return (CPlugin *)(pToken->ptr);
2566 void CPluginManager::OnLibraryAction(const char *lib, bool is_a_plugin, bool drop)
2568 List<CPlugin *>::iterator iter;
2585 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2587 for (iter=m_plugins.begin();
2588 iter!=m_plugins.end();
2591 CPlugin *pl = (*iter);
2592 if (pl->GetStatus() != Plugin_Running)
2596 IPluginContext *pContext = pl->GetBaseContext();
2597 IPluginFunction *pf = pContext->GetFunctionByName(name);
2602 uint32_t num_vars = pContext->GetPubVarsNum();
2603 for (uint32_t i=0; i<num_vars; i++)
2605 sp_pubvar_t *pubvar;
2606 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2610 if (is_a_plugin && strncmp(pubvar->name, "__pl_", 5) == 0)
2612 plc = (_pl *)pubvar->offs;
2618 pContext->LocalToString(plc->name, &str);
2619 if (strcmp(str, lib) != 0)
2623 pf->PushString(lib);
2626 else if (!is_a_plugin && strncmp(pubvar->name, "__ext_", 6) == 0)
2628 ext = (_ext *)pubvar->offs;
2634 pContext->LocalToString(ext->name, &str);
2635 if (strcmp(str, lib) != 0)
2639 pf->PushString(lib);
2646 bool CPluginManager::LibraryExists(const char *lib)
2648 List<CPlugin *>::iterator iter;
2650 for (iter=m_plugins.begin();
2651 iter!=m_plugins.end();
2654 CPlugin *pl = (*iter);
2655 if (pl->GetStatus() != Plugin_Running)
2659 List<String>::iterator s_iter;
2660 for (s_iter = pl->m_Libraries.begin();
2661 s_iter != pl->m_Libraries.end();
2664 if ((*s_iter).compare(lib) == 0)
2674 void CPluginManager::AllPluginsLoaded()
2676 List<CPlugin *>::iterator iter;
2679 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2682 pl->Call_OnAllPluginsLoaded();
2686 void CPluginManager::UnloadAll()
2688 List<CPlugin *>::iterator iter;
2689 while ( (iter = m_plugins.begin()) != m_plugins.end() )
2691 UnloadPlugin((*iter));
2695 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
2698 List<CPlugin *>::iterator iter;
2700 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)