3 * ================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * ================================================================
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License,
10 * version 3.0, as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to
21 * link the code of this program (as well as its derivative works) to
22 * "Half-Life 2," the "Source Engine," the "SourcePawn JIT," and any
23 * Game MODs that run on software by the Valve Corporation. You must
24 * obey the GNU General Public License in all respects for all other
25 * code used. Additionally, AlliedModders LLC grants this exception
26 * to all derivative works. AlliedModders LLC defines further
27 * exceptions, found in LICENSE.txt (as of this writing, version
28 * JULY-31-2007), or <http://www.sourcemod.net/license.php>.
34 #include "PluginSys.h"
36 #include "LibrarySys.h"
37 #include "HandleSys.h"
38 #include "ForwardSys.h"
39 #include "sourcemm_api.h"
40 #include "sourcemod.h"
41 #include "TextParsers.h"
43 #include "ExtensionSys.h"
44 #include "sm_srvcmds.h"
45 #include "sm_stringutil.h"
46 #include "ConCmdManager.h"
47 #include "PlayerManager.h"
48 #include "CoreConfig.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;
76 sec.pOwner = g_PluginSys.GetIdentity();
77 sec.pIdentity = sec.pOwner;
79 g_HandleSys.FreeHandle(m_handle, &sec);
80 g_ShareSys.DestroyIdentity(m_ident);
90 m_ctx.vm->FreeContext(m_ctx.ctx);
95 m_ctx.vm->AbortCompilation(m_ctx.co);
101 g_pSourcePawn->FreeFromMemory(m_plugin);
106 sm_trie_destroy(m_pProps);
108 for (size_t i=0; i<m_configs.size(); i++)
115 void CPlugin::InitIdentity()
119 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
120 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
121 m_ctx.base->SetIdentity(m_ident);
125 Handle_t CPlugin::GetMyHandle()
130 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
132 char fullpath[PLATFORM_MAX_PATH];
133 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
134 FILE *fp = fopen(fullpath, "rb");
136 CPlugin *pPlugin = new CPlugin(file);
142 snprintf(error, maxlength, "Unable to open file");
144 pPlugin->m_status = Plugin_BadLoad;
149 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
155 snprintf(error, maxlength, "Error %d while parsing plugin", err);
157 pPlugin->m_status = Plugin_BadLoad;
163 pPlugin->m_plugin = pl;
168 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
170 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
172 if (exists && remove)
174 sm_trie_delete(m_pProps, prop);
180 bool CPlugin::SetProperty(const char *prop, void *ptr)
182 return sm_trie_insert(m_pProps, prop, ptr);
185 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
192 /* :NOTICE: We will eventually need to change these natives
193 * for swapping in new contexts
195 if (m_ctx.co || m_ctx.ctx)
200 m_status = Plugin_Uncompiled;
203 m_ctx.co = vm->StartCompilation(m_plugin);
208 void CPlugin::CancelMyCompile()
215 m_ctx.vm->AbortCompilation(m_ctx.co);
220 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
228 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
231 memset(&m_ctx, 0, sizeof(m_ctx));
234 snprintf(error, maxlength, "JIT failed to compile (error %d)", err);
239 m_ctx.base = new BaseContext(m_ctx.ctx);
240 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
242 m_status = Plugin_Created;
250 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
252 PluginStatus old_status = m_status;
255 if (old_status == Plugin_Running)
257 /* Tell everyone we're now paused */
258 g_PluginSys._SetPauseState(this, true);
262 va_start(ap, error_fmt);
263 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
268 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
272 void CPlugin::UpdateInfo()
274 /* Now grab the info */
276 IPluginContext *base = GetBaseContext();
277 int err = base->FindPubvarByName("myinfo", &idx);
279 memset(&m_info, 0, sizeof(m_info));
281 if (err == SP_ERROR_NONE)
283 struct sm_plugininfo_c_t
291 sm_plugininfo_c_t *cinfo;
294 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
295 base->LocalToString(cinfo->name, (char **)&m_info.name);
296 base->LocalToString(cinfo->description, (char **)&m_info.description);
297 base->LocalToString(cinfo->author, (char **)&m_info.author);
298 base->LocalToString(cinfo->url, (char **)&m_info.url);
299 base->LocalToString(cinfo->version, (char **)&m_info.version);
302 m_info.author = m_info.author ? m_info.author : "";
303 m_info.description = m_info.description ? m_info.description : "";
304 m_info.name = m_info.name ? m_info.name : "";
305 m_info.url = m_info.url ? m_info.url : "";
306 m_info.version = m_info.version ? m_info.version : "";
309 void CPlugin::Call_OnPluginStart()
311 if (m_status != Plugin_Loaded)
316 m_status = Plugin_Running;
319 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
326 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
328 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
332 if ((pFunction = m_ctx.base->GetFunctionByName("OnMapStart")) != NULL)
334 pFunction->Execute(NULL);
337 if (SM_AreConfigsExecuted())
339 SM_ExecuteForPlugin(GetBaseContext());
344 void CPlugin::Call_OnPluginEnd()
346 if (m_status > Plugin_Paused)
352 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
358 pFunction->Execute(&result);
361 void CPlugin::Call_OnAllPluginsLoaded()
363 if (m_status > Plugin_Paused)
369 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnAllPluginsLoaded");
375 pFunction->Execute(&result);
378 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
380 if (m_status != Plugin_Created)
385 m_status = Plugin_Loaded;
389 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
396 pFunction->PushCell(m_handle);
397 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
398 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
399 pFunction->PushCell(maxlength);
400 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
405 if (!result || m_status != Plugin_Loaded)
413 const sp_plugin_t *CPlugin::GetPluginStructure()
418 IPluginContext *CPlugin::GetBaseContext()
423 sp_context_t *CPlugin::GetContext()
428 const char *CPlugin::GetFilename()
433 PluginType CPlugin::GetType()
438 const sm_plugininfo_t *CPlugin::GetPublicInfo()
443 unsigned int CPlugin::GetSerial()
448 PluginStatus CPlugin::GetStatus()
453 bool CPlugin::IsDebugging()
460 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
463 void CPlugin::LibraryActions(bool dropping)
465 List<String>::iterator iter;
466 for (iter = m_Libraries.begin();
467 iter != m_Libraries.end();
470 g_PluginSys.OnLibraryAction((*iter).c_str(), dropping);
474 bool CPlugin::SetPauseState(bool paused)
476 if (paused && GetStatus() != Plugin_Running)
479 } else if (!paused && GetStatus() != Plugin_Paused) {
485 LibraryActions(true);
488 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
492 pFunction->PushCell(paused ? 1 : 0);
493 pFunction->Execute(&result);
498 m_status = Plugin_Paused;
499 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
501 m_status = Plugin_Running;
502 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
505 g_PluginSys._SetPauseState(this, paused);
509 LibraryActions(false);
515 IdentityToken_t *CPlugin::GetIdentity()
520 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
528 snprintf(error, maxlength, "Plugin is not runnable.");
533 if (debug && IsDebugging())
537 snprintf(error, maxlength, "Plugin is already in debug mode.");
540 } else if (!debug && !IsDebugging()) {
543 snprintf(error, maxlength, "Plugins is already in production mode.");
548 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
549 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
553 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
558 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
562 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
563 new_ctx->hp = m_ctx.ctx->hp;
564 new_ctx->sp = m_ctx.ctx->sp;
565 new_ctx->frm = m_ctx.ctx->frm;
566 new_ctx->dbreak = m_ctx.ctx->dbreak;
567 new_ctx->context = m_ctx.ctx->context;
568 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
570 uint32_t nativeCount = m_plugin->info.natives_num;
571 for (uint32_t i=0; i<nativeCount; i++)
573 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
574 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
577 g_pVM->FreeContext(m_ctx.ctx);
579 m_ctx.base->SetContext(new_ctx);
585 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
593 bool CPlugin::IsRunnable()
595 return (m_status <= Plugin_Paused) ? true : false;
598 time_t CPlugin::GetFileTimeStamp()
600 char path[PLATFORM_MAX_PATH];
601 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
602 #ifdef PLATFORM_WINDOWS
604 if (_stat(path, &s) != 0)
605 #elif defined PLATFORM_POSIX
607 if (stat(path, &s) != 0)
616 time_t CPlugin::GetTimeStamp()
621 void CPlugin::SetTimeStamp(time_t t)
626 void CPlugin::AddLangFile(unsigned int index)
628 m_PhraseFiles.push_back(index);
631 size_t CPlugin::GetLangFileCount()
633 return m_PhraseFiles.size();
636 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
638 return m_PhraseFiles.at(index);
641 void CPlugin::DependencyDropped(CPlugin *pOwner)
648 List<String>::iterator reqlib_iter;
649 List<String>::iterator lib_iter;
650 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
652 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
654 if ((*reqlib_iter) == (*lib_iter))
656 m_LibraryMissing = true;
661 List<FakeNative *>::iterator iter;
665 unsigned int unbound = 0;
667 for (iter = pOwner->m_fakeNatives.begin();
668 iter != pOwner->m_fakeNatives.end();
672 /* Find this native! */
673 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
678 m_ctx.base->GetNativeByIndex(idx, &native);
680 native->status = SP_NATIVE_UNBOUND;
686 m_FakeNativesMissing = true;
689 /* :IDEA: in the future, add native trapping? */
690 if (m_FakeNativesMissing || m_LibraryMissing)
692 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
695 m_dependsOn.remove(pOwner);
698 unsigned int CPlugin::GetConfigCount()
700 return (unsigned int)m_configs.size();
703 AutoConfig *CPlugin::GetConfig(unsigned int i)
705 if (i >= GetConfigCount())
713 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
715 AutoConfig *c = new AutoConfig;
719 c->create = autoCreate;
721 m_configs.push_back(c);
728 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
734 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
739 bool CPluginManager::CPluginIterator::MorePlugins()
741 return (current != mylist->end());
744 void CPluginManager::CPluginIterator::NextPlugin()
749 void CPluginManager::CPluginIterator::Release()
751 g_PluginSys.ReleaseIterator(this);
754 CPluginManager::CPluginIterator::~CPluginIterator()
758 void CPluginManager::CPluginIterator::Reset()
760 current = mylist->begin();
767 CPluginManager::CPluginManager()
769 m_LoadLookup = sm_trie_create();
770 m_AllPluginsLoaded = false;
772 m_pNativeLookup = sm_trie_create();
775 CPluginManager::~CPluginManager()
778 * Ignore the fact that there might be plugins in the cache.
779 * This usually means that Core is not being unloaded properly, and everything
780 * will crash anyway. YAY
782 sm_trie_destroy(m_LoadLookup);
783 sm_trie_destroy(m_pNativeLookup);
785 CStack<CPluginManager::CPluginIterator *>::iterator iter;
786 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
793 void CPluginManager::Shutdown()
795 List<CPlugin *>::iterator iter;
797 while ((iter = m_plugins.begin()) != m_plugins.end())
803 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
805 /* First read in the database of plugin settings */
807 unsigned int line, col;
808 m_AllPluginsLoaded = false;
809 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
811 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
812 const char *err_msg = g_TextParser.GetSMCErrorString(err);
815 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
819 LoadPluginsFromDir(basedir, NULL);
822 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
824 char base_path[PLATFORM_MAX_PATH];
826 /* Form the current path to start reading from */
827 if (localpath == NULL)
829 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
831 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
834 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
839 g_LibSys.GetPlatformError(error, sizeof(error));
840 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
841 g_Logger.LogError("[SM] Platform returned error: %s", error);
845 while (dir->MoreFiles())
847 if (dir->IsEntryDirectory()
848 && (strcmp(dir->GetEntryName(), ".") != 0)
849 && (strcmp(dir->GetEntryName(), "..") != 0)
850 && (strcmp(dir->GetEntryName(), "disabled") != 0)
851 && (strcmp(dir->GetEntryName(), "optional") != 0))
853 char new_local[PLATFORM_MAX_PATH];
854 if (localpath == NULL)
856 /* If no path yet, don't add a former slash */
857 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
859 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
861 LoadPluginsFromDir(basedir, new_local);
862 } else if (dir->IsEntryFile()) {
863 const char *name = dir->GetEntryName();
864 size_t len = strlen(name);
866 && strcmp(&name[len-4], ".smx") == 0)
868 /* If the filename matches, load the plugin */
869 char plugin[PLATFORM_MAX_PATH];
870 if (localpath == NULL)
872 snprintf(plugin, sizeof(plugin), "%s", name);
874 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
876 LoadAutoPlugin(plugin);
881 g_LibSys.CloseDirectory(dir);
884 //well i have discovered that gabe newell is very fat, so i wrote this comment now
885 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
888 * Does this plugin already exist?
891 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
893 /* Check to see if we should try reloading it */
894 if (pPlugin->GetStatus() == Plugin_BadLoad
895 || pPlugin->GetStatus() == Plugin_Error
896 || pPlugin->GetStatus() == Plugin_Failed)
898 UnloadPlugin(pPlugin);
904 return LoadRes_AlreadyLoaded;
908 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
910 assert(pPlugin != NULL);
912 pPlugin->m_type = PluginType_MapUpdated;
914 ICompilation *co = NULL;
916 if (pPlugin->m_status == Plugin_Uncompiled)
918 co = pPlugin->StartMyCompile(g_pVM);
921 PluginSettings *pset;
922 unsigned int setcount = m_PluginInfo.GetSettingsNum();
923 for (unsigned int i=0; i<setcount; i++)
925 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
929 pPlugin->m_type = pset->type_val;
932 for (unsigned int j=0; j<pset->opts_num; j++)
934 const char *key, *val;
935 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
940 if (!g_pVM->SetCompilationOption(co, key, val))
944 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
946 pPlugin->CancelMyCompile();
954 /* Do the actual compiling */
957 pPlugin->FinishMyCompile(error, maxlength);
962 if (pPlugin->GetStatus() == Plugin_Created)
964 AddCoreNativesToPlugin(pPlugin);
965 pPlugin->InitIdentity();
966 if (pPlugin->Call_AskPluginLoad(error, maxlength))
968 /* Autoload any modules */
969 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
971 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
975 /* Save the time stamp */
976 time_t t = pPlugin->GetFileTimeStamp();
977 pPlugin->SetTimeStamp(t);
984 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
987 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
993 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
999 if (res == LoadRes_AlreadyLoaded)
1007 /* Run second pass if we need to */
1008 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
1010 if (!RunSecondPass(pl, error, maxlength))
1015 pl->Call_OnAllPluginsLoaded();
1021 void CPluginManager::LoadAutoPlugin(const char *plugin)
1025 char error[255] = "Unknown error";
1027 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
1029 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
1030 pl->SetErrorState(Plugin_Failed, "%s", error);
1033 if (res == LoadRes_Successful)
1039 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1041 List<IPluginsListener *>::iterator iter;
1042 IPluginsListener *pListener;
1044 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1046 pListener = (*iter);
1047 pListener->OnPluginCreated(pPlugin);
1050 m_plugins.push_back(pPlugin);
1051 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1054 void CPluginManager::LoadAll_SecondPass()
1056 List<CPlugin *>::iterator iter;
1060 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1063 if (pPlugin->GetStatus() == Plugin_Loaded)
1066 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1068 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1069 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1074 m_AllPluginsLoaded = true;
1077 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1086 IPluginContext *pBase = pPlugin->GetBaseContext();
1087 uint32_t num = pBase->GetPubVarsNum();
1088 sp_pubvar_t *pubvar;
1090 char pathfile[PLATFORM_MAX_PATH];
1092 for (uint32_t i=0; i<num; i++)
1094 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1098 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1100 pl = (_pl *)pubvar->offs;
1101 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1105 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1109 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1110 if (strcmp(pathfile, file) == 0)
1114 if (pl->required == false)
1116 IPluginFunction *pFunc;
1118 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1119 if ((pFunc=pBase->GetFunctionByName(buffer)))
1122 pFunc->Execute(&res);
1123 if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
1127 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1133 /* Check that we aren't registering the same library twice */
1134 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1136 pPlugin->m_RequiredLibs.push_back(name);
1140 List<CPlugin *>::iterator iter;
1143 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1146 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1156 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1167 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1169 /* Find any extensions this plugin needs */
1178 IPluginContext *pBase = pPlugin->GetBaseContext();
1179 uint32_t num = pBase->GetPubVarsNum();
1180 sp_pubvar_t *pubvar;
1182 char path[PLATFORM_MAX_PATH];
1184 for (uint32_t i=0; i<num; i++)
1186 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1190 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1192 ext = (_ext *)pubvar->offs;
1193 if (!ext->required && !ext->autoload)
1197 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1201 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1207 /* Attempt to auto-load if necessary */
1210 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1211 g_Extensions.LoadAutoExtension(path);
1213 } else if (pass == 2) {
1214 /* Is this required? */
1217 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1218 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1220 pExt = g_Extensions.FindExtensionByName(name);
1222 /* :TODO: should we bind to unloaded extensions?
1223 * Currently the extension manager will ignore this.
1225 if (!pExt || !pExt->IsRunning(NULL, 0))
1229 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1233 g_Extensions.BindChildPlugin(pExt, pPlugin);
1243 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1245 /* Second pass for extension requirements */
1246 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1251 /* Bind all extra natives */
1252 g_Extensions.BindAllNativesToPlugin(pPlugin);
1253 AddFakeNativesToPlugin(pPlugin);
1255 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1260 /* Find any unbound natives
1261 * Right now, these are not allowed
1263 IPluginContext *pContext = pPlugin->GetBaseContext();
1264 uint32_t num = pContext->GetNativesNum();
1265 sp_native_t *native;
1266 for (unsigned int i=0; i<num; i++)
1268 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1272 if (native->status == SP_NATIVE_UNBOUND
1273 && native->name[0] != '@'
1274 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1278 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1284 /* Finish by telling all listeners */
1285 List<IPluginsListener *>::iterator iter;
1286 IPluginsListener *pListener;
1287 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1289 pListener = (*iter);
1290 pListener->OnPluginLoaded(pPlugin);
1293 /* Tell this plugin to finish initializing itself */
1294 pPlugin->Call_OnPluginStart();
1296 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1297 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_fakeNatives.size())
1299 List<CPlugin *>::iterator pl_iter;
1301 for (pl_iter = m_plugins.begin();
1302 pl_iter != m_plugins.end();
1305 pOther = (*pl_iter);
1306 if ((pOther->GetStatus() == Plugin_Error
1307 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1308 || pOther->m_FakeNativesMissing)
1310 TryRefreshDependencies(pOther);
1315 /* Go through our libraries and tell other plugins they're added */
1316 List<String>::iterator s_iter;
1317 for (s_iter = pPlugin->m_Libraries.begin();
1318 s_iter != pPlugin->m_Libraries.end();
1321 OnLibraryAction((*s_iter).c_str(), false);
1327 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1329 List<sp_nativeinfo_t *>::iterator iter;
1331 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1333 sp_nativeinfo_t *natives = (*iter);
1334 IPluginContext *ctx = pPlugin->GetBaseContext();
1336 /* Attempt to bind every native! */
1337 while (natives[i].func != NULL)
1339 ctx->BindNative(&natives[i++]);
1344 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1346 assert(pPlugin->GetBaseContext() != NULL);
1348 AddFakeNativesToPlugin(pPlugin);
1350 List<String>::iterator lib_iter;
1351 List<String>::iterator req_iter;
1352 List<CPlugin *>::iterator pl_iter;
1354 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1357 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1360 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1362 if ((*req_iter) == (*lib_iter))
1370 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1375 /* Find any unbound natives
1376 * Right now, these are not allowed
1378 IPluginContext *pContext = pPlugin->GetBaseContext();
1379 uint32_t num = pContext->GetNativesNum();
1380 sp_native_t *native;
1381 for (unsigned int i=0; i<num; i++)
1383 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1387 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1389 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1394 if (pPlugin->GetStatus() == Plugin_Error)
1396 /* If we got here, all natives are okay again! */
1397 pPlugin->m_status = Plugin_Running;
1398 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1400 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1401 _SetPauseState(pPlugin, false);
1406 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1408 IPluginContext *pContext = pPlugin->GetBaseContext();
1409 sp_nativeinfo_t native;
1411 List<FakeNative *>::iterator iter;
1412 FakeNative *pNative;
1414 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1417 ctx = pNative->ctx->GetContext();
1418 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1420 /* Ignore natives in paused plugins */
1423 native.name = pNative->name.c_str();
1424 native.func = pNative->func;
1425 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1428 pContext->FindNativeByName(native.name, &idx);
1429 if (pPlugin->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL)
1431 WeakNative wkn(pPlugin, idx);
1432 GetPluginByCtx(ctx)->m_WeakNatives.push_back(wkn);
1435 /* Add us as a dependency, but we're careful not to do this circularly! */
1436 if (pNative->ctx != pContext)
1438 CPlugin *pOther = GetPluginByCtx(ctx);
1439 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1441 pOther->m_dependents.push_back(pPlugin);
1443 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1445 pPlugin->m_dependsOn.push_back(pOther);
1452 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1454 CPlugin *pPlugin = (CPlugin *)plugin;
1456 /* This prevents removal during insertion or anything else weird */
1457 if (m_plugins.find(pPlugin) == m_plugins.end())
1462 /* Remove us from the lookup table and linked list */
1463 m_plugins.remove(pPlugin);
1464 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1466 /* Go through our libraries and tell other plugins they're gone */
1467 List<String>::iterator s_iter;
1468 for (s_iter = pPlugin->m_Libraries.begin();
1469 s_iter != pPlugin->m_Libraries.end();
1472 OnLibraryAction((*s_iter).c_str(), true);
1475 /* Go through all dependent plugins and tell them this plugin is now gone */
1476 List<CPlugin *>::iterator pl_iter;
1478 for (pl_iter = pPlugin->m_dependents.begin();
1479 pl_iter != pPlugin->m_dependents.end();
1482 pOther = (*pl_iter);
1483 pOther->DependencyDropped(pPlugin);
1486 /* Tell everyone we depend on that we no longer exist */
1487 for (pl_iter = pPlugin->m_dependsOn.begin();
1488 pl_iter != pPlugin->m_dependsOn.end();
1491 pOther = (*pl_iter);
1492 pOther->m_dependents.remove(pPlugin);
1495 /* Remove weak references to us */
1496 for (pl_iter = m_plugins.begin();
1497 pl_iter != m_plugins.end();
1500 pOther = (*pl_iter);
1501 List<WeakNative>::iterator wk_iter = pOther->m_WeakNatives.begin();
1502 while (wk_iter != pOther->m_WeakNatives.end())
1504 if ((*wk_iter).pl == pPlugin)
1506 wk_iter = pOther->m_WeakNatives.erase(wk_iter);
1513 List<IPluginsListener *>::iterator iter;
1514 IPluginsListener *pListener;
1516 if (pPlugin->GetStatus() <= Plugin_Error)
1518 /* Notify listeners of unloading */
1519 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1521 pListener = (*iter);
1522 pListener->OnPluginUnloaded(pPlugin);
1525 pPlugin->Call_OnPluginEnd();
1528 /* Unbound weak natives */
1529 List<WeakNative>::iterator wk_iter;
1530 for (wk_iter=pPlugin->m_WeakNatives.begin(); wk_iter!=pPlugin->m_WeakNatives.end(); wk_iter++)
1532 WeakNative & wkn = (*wk_iter);
1533 sp_context_t *ctx = wkn.pl->GetContext();
1534 ctx->natives[wkn.idx].status = SP_NATIVE_UNBOUND;
1535 wkn.pl->m_FakeNativesMissing = true;
1538 /* Remove all of our native functions */
1539 List<FakeNative *>::iterator fn_iter;
1540 FakeNative *pNative;
1541 for (fn_iter = pPlugin->m_fakeNatives.begin();
1542 fn_iter != pPlugin->m_fakeNatives.end();
1545 pNative = (*fn_iter);
1546 m_Natives.remove(pNative);
1547 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1548 g_pVM->DestroyFakeNative(pNative->func);
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)
1567 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1571 unsigned int CPluginManager::GetPluginCount()
1573 return m_plugins.size();
1576 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1578 m_listeners.push_back(listener);
1581 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1583 m_listeners.remove(listener);
1586 IPluginIterator *CPluginManager::GetPluginIterator()
1588 if (m_iters.empty())
1590 return new CPluginIterator(&m_plugins);
1592 CPluginIterator *iter = m_iters.front();
1599 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1604 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1606 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1607 size_t alias_len = 0;
1608 size_t local_len = 0;
1610 const char *ptr = alias;
1611 unsigned int alias_explicit_paths = 0;
1612 unsigned int alias_path_end = 0;
1613 while (*ptr != '\0')
1615 if (*ptr == '\\' || *ptr == '/')
1617 alias_explicit_paths++;
1618 alias_path_end = alias_len;
1624 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1626 /* Trailing slash is totally invalid here */
1631 unsigned int local_explicit_paths = 0;
1632 unsigned int local_path_end = 0;
1633 while (*ptr != '\0')
1635 if (*ptr == '\\' || *ptr == '/')
1637 local_explicit_paths++;
1638 local_path_end = local_len;
1644 /* If the alias has more explicit paths than the real path,
1645 * no match will be possible.
1647 if (alias_explicit_paths > local_explicit_paths)
1652 if (alias_explicit_paths)
1654 /* We need to find if the paths match now. For example, these should all match:
1656 * csdm optional/csdm
1657 * csdm/ban optional/crab/csdm/ban
1659 const char *aliasptr = alias;
1660 const char *localptr = localpath;
1664 if (*aliasptr != *localptr)
1666 /* We have to knock one path off */
1667 local_explicit_paths--;
1668 if (alias_explicit_paths > local_explicit_paths)
1670 /* Skip out if we're gonna have an impossible match */
1673 /* Eat up localptr tokens until we get a result */
1674 while (((localptr - localpath) < (int)local_path_end)
1676 && *localptr != '\\')
1680 /* Check if we hit the end of our searchable area.
1681 * This probably isn't possible because of the path
1682 * count check, but it's a good idea anyway.
1684 if ((localptr - localpath) >= (int)local_path_end)
1688 /* Consume the slash token */
1691 /* Reset the alias pointer so we can continue consuming */
1697 * This is safe because if localptr terminates early, aliasptr will too
1701 /* We should never reach the end of the string because of this check. */
1702 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1703 bool localend = (localptr - localpath) > (int)local_path_end;
1704 if (aliasend || localend)
1706 if (aliasend && localend)
1708 /* we matched, and we can break out now */
1712 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1717 /* If we got here, it's safe to compare the next two tokens */
1718 if (*localptr != *aliasptr)
1729 /* If we got here, it's time to compare filenames */
1730 const char *aliasptr = alias;
1731 const char *localptr = localpath;
1733 if (alias_explicit_paths)
1735 aliasptr = &alias[alias_path_end + 1];
1738 if (local_explicit_paths)
1740 localptr = &localpath[local_path_end + 1];
1745 if (*aliasptr == '*')
1747 /* First, see if this is the last character */
1748 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1750 /* If so, there's no need to match anything else */
1753 /* Otherwise, we need to search for an appropriate matching sequence in local.
1754 * Note that we only need to search up to the next asterisk.
1758 const char *local_orig = localptr;
1762 while (*aliasptr != '\0' && *aliasptr != '*')
1764 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1765 if (*aliasptr != *localptr)
1775 /* If we didn't get a match, we need to advance the search stream.
1776 * This will let us skip tokens while still searching for another match.
1778 localptr = ++local_orig;
1779 /* Make sure we don't go out of bounds */
1780 if (*localptr == '\0')
1791 /* If we got a match, move on to the next token */
1794 } else if (*aliasptr == '\0') {
1795 if (*localptr == '\0'
1797 strcmp(localptr, ".smx") == 0)
1803 } else if (*aliasptr != *localptr) {
1813 bool CPluginManager::IsLateLoadTime() const
1815 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1818 void CPluginManager::OnSourceModAllInitialized()
1820 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1823 g_HandleSys.InitAccessDefaults(NULL, &sec);
1825 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1826 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1828 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1829 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1831 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1833 g_ShareSys.AddInterface(NULL, this);
1836 void CPluginManager::OnSourceModShutdown()
1838 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1840 List<CPlugin *>::iterator iter;
1841 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1843 UnloadPlugin((*iter));
1846 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1847 g_ShareSys.DestroyIdentType(g_PluginIdent);
1848 g_ShareSys.DestroyIdentity(m_MyIdent);
1851 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1853 /* We don't care about the internal object, actually */
1856 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1858 m_natives.push_back(natives);
1861 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1869 sec.pIdentity = m_MyIdent;
1871 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1884 CPlugin *CPluginManager::GetPluginByOrder(int num)
1886 if (num < 1 || num > (int)GetPluginCount())
1894 IPluginIterator *iter = GetPluginIterator();
1895 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1897 pl = (CPlugin *)(iter->GetPlugin());
1903 const char *CPluginManager::GetStatusText(PluginStatus st)
1907 case Plugin_Running:
1913 case Plugin_Uncompiled:
1914 return "Uncompiled";
1915 case Plugin_BadLoad:
1925 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1929 const char *cmd = g_RootMenu.GetArgument(2);
1930 if (strcmp(cmd, "list") == 0)
1933 unsigned int id = 1;
1934 int plnum = GetPluginCount();
1938 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1941 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1944 IPluginIterator *iter = GetPluginIterator();
1945 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1947 IPlugin *pl = iter->GetPlugin();
1948 assert(pl->GetStatus() != Plugin_Created);
1950 const sm_plugininfo_t *info = pl->GetPublicInfo();
1951 if (pl->GetStatus() != Plugin_Running)
1953 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1955 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1957 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1958 if (IS_STR_FILLED(info->version))
1960 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1962 if (IS_STR_FILLED(info->author))
1964 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1966 g_RootMenu.ConsolePrint("%s", buffer);
1971 } else if (strcmp(cmd, "load") == 0) {
1974 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1980 const char *filename = g_RootMenu.GetArgument(3);
1982 char pluginfile[256];
1983 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1984 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1986 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1990 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1996 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1998 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
2002 } else if (strcmp(cmd, "unload") == 0) {
2005 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
2010 int num = atoi(g_RootMenu.GetArgument(3));
2011 if (num < 1 || num > (int)GetPluginCount())
2013 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
2017 IPluginIterator *iter = GetPluginIterator();
2018 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
2020 IPlugin *pl = iter->GetPlugin();
2022 char name[PLATFORM_MAX_PATH];
2023 const sm_plugininfo_t *info = pl->GetPublicInfo();
2024 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2026 if (UnloadPlugin(pl))
2028 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
2030 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
2035 } else if (strcmp(cmd, "info") == 0) {
2038 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2042 int num = atoi(g_RootMenu.GetArgument(3));
2043 if (num < 1 || num > (int)GetPluginCount())
2045 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
2049 CPlugin *pl = GetPluginByOrder(num);
2050 const sm_plugininfo_t *info = pl->GetPublicInfo();
2052 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2053 if (pl->GetStatus() <= Plugin_Error)
2055 if (IS_STR_FILLED(info->name))
2057 if (IS_STR_FILLED(info->description))
2059 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2061 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2064 if (IS_STR_FILLED(info->author))
2066 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2068 if (IS_STR_FILLED(info->version))
2070 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2072 if (IS_STR_FILLED(info->url))
2074 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2076 if (pl->GetStatus() == Plugin_Error)
2078 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2080 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
2081 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
2083 const char *typestr = "";
2084 switch (pl->GetType())
2086 case PluginType_MapUpdated:
2087 typestr = "Map Change if Updated";
2089 case PluginType_MapOnly:
2090 typestr = "Map Change";
2092 case PluginType_Private:
2093 case PluginType_Global:
2098 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2101 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2102 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2103 info->name ? info->name : "<none>",
2104 info->version ? info->version : "<none>");
2105 if (IS_STR_FILLED(info->url))
2107 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2112 } else if (strcmp(cmd, "debug") == 0) {
2115 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
2119 int num = atoi(g_RootMenu.GetArgument(3));
2120 if (num < 1 || num > (int)GetPluginCount())
2122 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
2127 const char *mode = g_RootMenu.GetArgument(4);
2128 if ((res=strcmp("on", mode)) && strcmp("off", mode))
2130 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
2142 CPlugin *pl = GetPluginByOrder(num);
2143 if (debug && pl->IsDebugging())
2145 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
2147 } else if (!debug && !pl->IsDebugging()) {
2148 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
2153 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
2155 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
2158 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
2159 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
2165 /* Draw the main menu */
2166 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2167 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2168 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2169 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2170 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2171 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
2174 void CPluginManager::ReloadOrUnloadPlugins()
2176 List<CPlugin *>::iterator iter;
2177 List<CPlugin *> tmp_list = m_plugins;
2181 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2184 if (pl->GetType() == PluginType_MapOnly)
2186 UnloadPlugin((IPlugin *)pl);
2187 } else if (pl->GetType() == PluginType_MapUpdated) {
2188 t = pl->GetFileTimeStamp();
2189 if (!t || t > pl->GetTimeStamp())
2191 pl->SetTimeStamp(t);
2192 UnloadPlugin((IPlugin *)pl);
2198 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2200 List<IPluginsListener *>::iterator iter;
2201 IPluginsListener *pListener;
2202 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2204 pListener = (*iter);
2205 pListener->OnPluginPauseChange(pl, paused);
2209 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
2211 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
2216 FakeNative *pNative = new FakeNative;
2218 pNative->func = g_pVM->CreateFakeNative(func, pNative);
2225 pNative->call = pFunction;
2226 pNative->name.assign(name);
2227 pNative->ctx = pFunction->GetParentContext();
2229 m_Natives.push_back(pNative);
2230 sm_trie_insert(m_pNativeLookup, name,pNative);
2232 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
2233 pPlugin->m_fakeNatives.push_back(pNative);
2238 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2240 List<CPlugin *>::iterator iter;
2242 IPluginFunction *pFunction;
2244 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2248 if (pPlugin->GetStatus() <= Plugin_Paused)
2250 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2254 pForward->AddFunction(pFunction);
2260 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2262 if (pToken->type != g_PluginIdent)
2267 return (CPlugin *)(pToken->ptr);
2270 void CPluginManager::OnLibraryAction(const char *lib, bool drop)
2272 List<CPlugin *>::iterator iter;
2281 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2283 for (iter=m_plugins.begin();
2284 iter!=m_plugins.end();
2287 CPlugin *pl = (*iter);
2288 if (pl->GetStatus() != Plugin_Running)
2292 IPluginContext *pContext = pl->GetBaseContext();
2293 IPluginFunction *pf = pContext->GetFunctionByName(name);
2298 uint32_t num_vars = pContext->GetPubVarsNum();
2299 for (uint32_t i=0; i<num_vars; i++)
2301 sp_pubvar_t *pubvar;
2302 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2306 if (strncmp(pubvar->name, "__pl_", 5) != 0)
2310 plc = (_pl *)pubvar->offs;
2316 pContext->LocalToString(plc->name, &str);
2317 if (strcmp(str, lib) != 0)
2321 pf->PushString(lib);
2327 bool CPluginManager::LibraryExists(const char *lib)
2329 List<CPlugin *>::iterator iter;
2331 for (iter=m_plugins.begin();
2332 iter!=m_plugins.end();
2335 CPlugin *pl = (*iter);
2336 if (pl->GetStatus() != Plugin_Running)
2340 List<String>::iterator s_iter;
2341 for (s_iter = pl->m_Libraries.begin();
2342 s_iter != pl->m_Libraries.end();
2345 if ((*s_iter).compare(lib) == 0)
2355 void CPluginManager::AllPluginsLoaded()
2357 List<CPlugin *>::iterator iter;
2360 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2363 pl->Call_OnAllPluginsLoaded();