2 * ===============================================================
3 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
4 * ===============================================================
6 * This file is not open source and may not be copied without explicit
7 * written permission of AlliedModders LLC. This file may not be redistributed
8 * in whole or significant part.
9 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
15 #include "PluginSys.h"
17 #include "LibrarySys.h"
18 #include "HandleSys.h"
19 #include "sourcemm_api.h"
20 #include "sourcemod.h"
21 #include "TextParsers.h"
23 #include "ExtensionSys.h"
24 #include "sm_srvcmds.h"
25 #include "sm_stringutil.h"
27 CPluginManager g_PluginSys;
28 HandleType_t g_PluginType = 0;
29 IdentityType_t g_PluginIdent = 0;
31 CPlugin::CPlugin(const char *file)
33 static int MySerial = 0;
35 m_type = PluginType_Private;
36 m_status = Plugin_Uncompiled;
37 m_serial = ++MySerial;
39 m_errormsg[256] = '\0';
40 snprintf(m_filename, sizeof(m_filename), "%s", file);
43 m_pProps = sm_trie_create();
44 m_FakeNativesMissing = false;
52 sec.pOwner = g_PluginSys.GetIdentity();
53 sec.pIdentity = sec.pOwner;
55 g_HandleSys.FreeHandle(m_handle, &sec);
56 g_ShareSys.DestroyIdentity(m_ident);
66 m_ctx.vm->FreeContext(m_ctx.ctx);
71 m_ctx.vm->AbortCompilation(m_ctx.co);
77 g_pSourcePawn->FreeFromMemory(m_plugin);
82 sm_trie_destroy(m_pProps);
86 void CPlugin::InitIdentity()
90 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent);
91 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
92 m_ctx.base->SetIdentity(m_ident);
96 Handle_t CPlugin::GetMyHandle()
101 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
103 char fullpath[PLATFORM_MAX_PATH+1];
104 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
105 FILE *fp = fopen(fullpath, "rb");
107 CPlugin *pPlugin = new CPlugin(file);
113 snprintf(error, maxlength, "Unable to open file");
115 pPlugin->m_status = Plugin_BadLoad;
120 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
126 snprintf(error, maxlength, "Error %d while parsing plugin", err);
128 pPlugin->m_status = Plugin_BadLoad;
134 pPlugin->m_plugin = pl;
139 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
141 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
143 if (exists && remove)
145 sm_trie_delete(m_pProps, prop);
151 bool CPlugin::SetProperty(const char *prop, void *ptr)
153 return sm_trie_insert(m_pProps, prop, ptr);
156 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
163 /* :NOTICE: We will eventually need to change these natives
164 * for swapping in new contexts
166 if (m_ctx.co || m_ctx.ctx)
171 m_status = Plugin_Uncompiled;
174 m_ctx.co = vm->StartCompilation(m_plugin);
179 void CPlugin::CancelMyCompile()
186 m_ctx.vm->AbortCompilation(m_ctx.co);
191 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
199 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
202 memset(&m_ctx, 0, sizeof(m_ctx));
205 snprintf(error, maxlength, "Failed to compile (error %d)", err);
210 m_ctx.base = new BaseContext(m_ctx.ctx);
211 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
213 m_status = Plugin_Created;
221 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
223 PluginStatus old_status = m_status;
226 if (old_status == Plugin_Running)
228 /* Tell everyone we're now paused */
229 g_PluginSys._SetPauseState(this, true);
233 va_start(ap, error_fmt);
234 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
239 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
243 void CPlugin::UpdateInfo()
245 /* Now grab the info */
247 IPluginContext *base = GetBaseContext();
248 int err = base->FindPubvarByName("myinfo", &idx);
250 memset(&m_info, 0, sizeof(m_info));
252 if (err == SP_ERROR_NONE)
254 struct sm_plugininfo_c_t
262 sm_plugininfo_c_t *cinfo;
265 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
266 base->LocalToString(cinfo->name, (char **)&m_info.name);
267 base->LocalToString(cinfo->description, (char **)&m_info.description);
268 base->LocalToString(cinfo->author, (char **)&m_info.author);
269 base->LocalToString(cinfo->url, (char **)&m_info.url);
270 base->LocalToString(cinfo->version, (char **)&m_info.version);
273 m_info.author = m_info.author ? m_info.author : "";
274 m_info.description = m_info.description ? m_info.description : "";
275 m_info.name = m_info.name ? m_info.name : "";
276 m_info.url = m_info.url ? m_info.url : "";
277 m_info.version = m_info.version ? m_info.version : "";
280 void CPlugin::Call_OnPluginStart()
282 if (m_status != Plugin_Loaded)
287 m_status = Plugin_Running;
290 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
296 pFunction->Execute(&result);
299 void CPlugin::Call_OnPluginEnd()
301 if (m_status < Plugin_Paused)
307 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
313 pFunction->Execute(&result);
316 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
318 if (m_status != Plugin_Created)
323 m_status = Plugin_Loaded;
327 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
334 pFunction->PushCell(m_handle);
335 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
336 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
337 pFunction->PushCell(maxlength);
338 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
343 if (!result || m_status != Plugin_Loaded)
351 const sp_plugin_t *CPlugin::GetPluginStructure() const
356 IPluginContext *CPlugin::GetBaseContext() const
361 sp_context_t *CPlugin::GetContext() const
366 const char *CPlugin::GetFilename() const
371 PluginType CPlugin::GetType() const
376 const sm_plugininfo_t *CPlugin::GetPublicInfo() const
381 unsigned int CPlugin::GetSerial() const
386 PluginStatus CPlugin::GetStatus() const
391 bool CPlugin::IsDebugging() const
398 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
401 bool CPlugin::SetPauseState(bool paused)
403 if (paused && GetStatus() != Plugin_Paused)
406 } else if (!paused && GetStatus() != Plugin_Running) {
410 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
414 pFunction->PushCell(paused ? 1 : 0);
415 pFunction->Execute(&result);
420 m_status = Plugin_Paused;
421 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
423 m_status = Plugin_Running;
424 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
427 g_PluginSys._SetPauseState(this, paused);
432 IdentityToken_t *CPlugin::GetIdentity() const
437 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
445 snprintf(error, maxlength, "Plugin is not runnable.");
450 if (debug && IsDebugging())
454 snprintf(error, maxlength, "Plugin is already in debug mode.");
457 } else if (!debug && !IsDebugging()) {
460 snprintf(error, maxlength, "Plugins is already in production mode.");
465 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
466 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
470 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
475 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
479 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
480 new_ctx->hp = m_ctx.ctx->hp;
481 new_ctx->sp = m_ctx.ctx->sp;
482 new_ctx->frm = m_ctx.ctx->frm;
483 new_ctx->dbreak = m_ctx.ctx->dbreak;
484 new_ctx->context = m_ctx.ctx->context;
485 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
487 g_pVM->FreeContext(m_ctx.ctx);
489 m_ctx.base->SetContext(new_ctx);
495 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
503 bool CPlugin::IsRunnable() const
505 return (m_status <= Plugin_Paused) ? true : false;
508 time_t CPlugin::GetFileTimeStamp()
510 char path[PLATFORM_MAX_PATH+1];
511 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
512 #ifdef PLATFORM_WINDOWS
514 if (_stat(path, &s) != 0)
515 #elif defined PLATFORM_POSIX
517 if (stat(path, &s) != 0)
526 time_t CPlugin::GetTimeStamp() const
531 void CPlugin::SetTimeStamp(time_t t)
536 void CPlugin::AddLangFile(unsigned int index)
538 m_PhraseFiles.push_back(index);
541 size_t CPlugin::GetLangFileCount() const
543 return m_PhraseFiles.size();
546 unsigned int CPlugin::GetLangFileByIndex(unsigned int index) const
548 return m_PhraseFiles.at(index);
551 void CPlugin::DependencyDropped(CPlugin *pOwner)
558 List<FakeNative *>::iterator iter;
562 unsigned int unbound = 0;
564 for (iter = pOwner->m_fakeNatives.begin();
565 iter != pOwner->m_fakeNatives.end();
569 /* Find this native! */
570 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
575 m_ctx.base->GetNativeByIndex(idx, &native);
577 native->status = SP_NATIVE_UNBOUND;
581 /* :IDEA: in the future, add native trapping? */
584 m_FakeNativesMissing = true;
585 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
588 m_dependsOn.remove(pOwner);
595 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
601 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
606 bool CPluginManager::CPluginIterator::MorePlugins()
608 return (current != mylist->end());
611 void CPluginManager::CPluginIterator::NextPlugin()
616 void CPluginManager::CPluginIterator::Release()
618 g_PluginSys.ReleaseIterator(this);
621 CPluginManager::CPluginIterator::~CPluginIterator()
625 void CPluginManager::CPluginIterator::Reset()
627 current = mylist->begin();
634 CPluginManager::CPluginManager()
636 m_LoadLookup = sm_trie_create();
637 m_AllPluginsLoaded = false;
639 m_pNativeLookup = sm_trie_create();
642 CPluginManager::~CPluginManager()
645 * Ignore the fact that there might be plugins in the cache.
646 * This usually means that Core is not being unloaded properly, and everything
647 * will crash anyway. YAY
649 sm_trie_destroy(m_LoadLookup);
650 sm_trie_destroy(m_pNativeLookup);
653 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
655 /* First read in the database of plugin settings */
657 unsigned int line, col;
658 m_AllPluginsLoaded = false;
659 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
661 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
662 const char *err_msg = g_TextParser.GetSMCErrorString(err);
665 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
669 LoadPluginsFromDir(basedir, NULL);
672 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
674 char base_path[PLATFORM_MAX_PATH+1];
676 /* Form the current path to start reading from */
677 if (localpath == NULL)
679 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
681 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
684 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
689 g_LibSys.GetPlatformError(error, sizeof(error));
690 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
691 g_Logger.LogError("[SM] Platform returned error: %s", error);
695 while (dir->MoreFiles())
697 if (dir->IsEntryDirectory()
698 && (strcmp(dir->GetEntryName(), ".") != 0)
699 && (strcmp(dir->GetEntryName(), "..") != 0)
700 && (strcmp(dir->GetEntryName(), "disabled") != 0)
701 && (strcmp(dir->GetEntryName(), "optional") != 0))
703 char new_local[PLATFORM_MAX_PATH+1];
704 if (localpath == NULL)
706 /* If no path yet, don't add a former slash */
707 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
709 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
711 LoadPluginsFromDir(basedir, new_local);
712 } else if (dir->IsEntryFile()) {
713 const char *name = dir->GetEntryName();
714 size_t len = strlen(name);
716 && strcmp(&name[len-4], ".smx") == 0)
718 /* If the filename matches, load the plugin */
719 char plugin[PLATFORM_MAX_PATH+1];
720 if (localpath == NULL)
722 snprintf(plugin, sizeof(plugin), "%s", name);
724 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
726 LoadAutoPlugin(plugin);
731 g_LibSys.CloseDirectory(dir);
734 //well i have discovered that gabe newell is very fat, so i wrote this comment now
735 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t err_max)
738 * Does this plugin already exist?
741 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
743 /* Check to see if we should try reloading it */
744 if (pPlugin->GetStatus() == Plugin_BadLoad
745 || pPlugin->GetStatus() == Plugin_Error
746 || pPlugin->GetStatus() == Plugin_Failed)
748 UnloadPlugin(pPlugin);
754 return LoadRes_AlreadyLoaded;
758 pPlugin = CPlugin::CreatePlugin(path, error, err_max);
760 assert(pPlugin != NULL);
762 pPlugin->m_type = PluginType_MapUpdated;
764 ICompilation *co = NULL;
766 if (pPlugin->m_status == Plugin_Uncompiled)
768 co = pPlugin->StartMyCompile(g_pVM);
771 PluginSettings *pset;
772 unsigned int setcount = m_PluginInfo.GetSettingsNum();
773 for (unsigned int i=0; i<setcount; i++)
775 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
779 pPlugin->m_type = pset->type_val;
782 for (unsigned int j=0; j<pset->opts_num; j++)
784 const char *key, *val;
785 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
790 if (!g_pVM->SetCompilationOption(co, key, val))
794 snprintf(error, err_max, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
796 pPlugin->CancelMyCompile();
804 /* Do the actual compiling */
807 pPlugin->FinishMyCompile(NULL, 0);
812 if (pPlugin->GetStatus() == Plugin_Created)
814 AddCoreNativesToPlugin(pPlugin);
815 pPlugin->InitIdentity();
816 if (pPlugin->Call_AskPluginLoad(error, err_max))
818 /* Autoload any modules */
819 LoadOrRequireExtensions(pPlugin, 1, error, err_max);
823 /* Save the time stamp */
824 time_t t = pPlugin->GetFileTimeStamp();
825 pPlugin->SetTimeStamp(t);
832 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
835 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t err_max, bool *wasloaded)
841 if ((res=_LoadPlugin(&pl, path, debug, type, error, err_max)) == LoadRes_Failure)
847 if (res == LoadRes_AlreadyLoaded)
855 /* Run second pass if we need to */
856 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
858 if (!RunSecondPass(pl, error, err_max))
868 void CPluginManager::LoadAutoPlugin(const char *plugin)
872 char error[255] = "Unknown error";
874 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
876 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
877 pl->SetErrorState(Plugin_Failed, "%s", error);
880 if (res == LoadRes_Successful)
886 void CPluginManager::AddPlugin(CPlugin *pPlugin)
888 List<IPluginsListener *>::iterator iter;
889 IPluginsListener *pListener;
891 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
894 pListener->OnPluginCreated(pPlugin);
897 m_plugins.push_back(pPlugin);
898 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
901 void CPluginManager::LoadAll_SecondPass()
903 List<CPlugin *>::iterator iter;
907 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
910 if (pPlugin->GetStatus() == Plugin_Loaded)
913 if (!RunSecondPass(pPlugin, error, sizeof(error)))
915 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
916 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
921 m_AllPluginsLoaded = true;
924 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
926 /* Find any extensions this plugin needs */
935 IPluginContext *pBase = pPlugin->GetBaseContext();
936 uint32_t num = pBase->GetPubVarsNum();
939 char path[PLATFORM_MAX_PATH+1];
941 for (uint32_t i=0; i<num; i++)
943 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
947 if (strncmp(pubvar->name, "__ext_", 6) == 0)
949 ext = (_ext *)pubvar->offs;
950 if (!ext->required && !ext->autoload)
954 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
958 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
964 /* Attempt to auto-load if necessary */
967 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
968 g_Extensions.LoadAutoExtension(path);
970 } else if (pass == 2) {
971 /* Is this required? */
974 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
975 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
977 pExt = g_Extensions.FindExtensionByName(name);
979 /* :TODO: should we bind to unloaded extensions?
980 * Currently the extension manager will ignore this.
982 if (!pExt || !pExt->IsRunning(NULL, 0))
986 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
990 g_Extensions.BindChildPlugin(pExt, pPlugin);
1000 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1002 /* Second pass for extension requirements */
1003 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1008 /* Bind all extra natives */
1009 g_Extensions.BindAllNativesToPlugin(pPlugin);
1010 AddFakeNativesToPlugin(pPlugin);
1012 /* Find any unbound natives
1013 * Right now, these are not allowed
1015 IPluginContext *pContext = pPlugin->GetBaseContext();
1016 uint32_t num = pContext->GetNativesNum();
1017 sp_native_t *native;
1018 for (unsigned int i=0; i<num; i++)
1020 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1024 if (native->status == SP_NATIVE_UNBOUND)
1028 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1034 /* Finish by telling all listeners */
1035 List<IPluginsListener *>::iterator iter;
1036 IPluginsListener *pListener;
1037 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1039 pListener = (*iter);
1040 pListener->OnPluginLoaded(pPlugin);
1043 /* Tell this plugin to finish initializing itself */
1044 pPlugin->Call_OnPluginStart();
1046 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1047 if (pPlugin->m_fakeNatives.size())
1049 List<CPlugin *>::iterator pl_iter;
1051 for (pl_iter = m_plugins.begin();
1052 pl_iter != m_plugins.end();
1055 pOther = (*pl_iter);
1056 if (pOther->GetStatus() == Plugin_Error
1057 && pOther->m_FakeNativesMissing)
1059 TryRefreshNatives(pOther);
1067 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1069 List<sp_nativeinfo_t *>::iterator iter;
1071 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1073 sp_nativeinfo_t *natives = (*iter);
1074 IPluginContext *ctx = pPlugin->GetBaseContext();
1076 /* Attempt to bind every native! */
1077 while (natives[i].func != NULL)
1079 ctx->BindNative(&natives[i++]);
1084 void CPluginManager::TryRefreshNatives(CPlugin *pPlugin)
1086 assert(pPlugin->GetBaseContext() != NULL);
1088 AddFakeNativesToPlugin(pPlugin);
1090 /* Find any unbound natives
1091 * Right now, these are not allowed
1093 IPluginContext *pContext = pPlugin->GetBaseContext();
1094 uint32_t num = pContext->GetNativesNum();
1095 sp_native_t *native;
1096 for (unsigned int i=0; i<num; i++)
1098 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1102 if (native->status == SP_NATIVE_UNBOUND)
1104 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1109 /* If we got here, all natives are okay again! */
1110 pPlugin->m_status = Plugin_Running;
1111 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1113 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1114 _SetPauseState(pPlugin, false);
1118 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1120 IPluginContext *pContext = pPlugin->GetBaseContext();
1121 sp_nativeinfo_t native;
1123 List<FakeNative *>::iterator iter;
1124 FakeNative *pNative;
1126 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1129 ctx = pNative->ctx->GetContext();
1130 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1132 /* Ignore natives in paused plugins */
1135 native.name = pNative->name.c_str();
1136 native.func = pNative->func;
1137 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1139 /* Add us as a dependency, but we're careful not to do this circularly! */
1140 if (pNative->ctx != pContext)
1142 CPlugin *pOther = GetPluginByCtx(ctx);
1143 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1145 pOther->m_dependents.push_back(pPlugin);
1147 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1149 pPlugin->m_dependsOn.push_back(pOther);
1156 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1158 CPlugin *pPlugin = (CPlugin *)plugin;
1160 /* This prevents removal during insertion or anything else weird */
1161 if (m_plugins.find(pPlugin) == m_plugins.end())
1166 /* Remove us from the lookup table and linked list */
1167 m_plugins.remove(pPlugin);
1168 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1170 /* Go through all dependent plugins and tell them this plugin is now gone */
1171 List<CPlugin *>::iterator pl_iter;
1173 for (pl_iter = pPlugin->m_dependents.begin();
1174 pl_iter != pPlugin->m_dependents.end();
1177 pOther = (*pl_iter);
1178 pOther->DependencyDropped(pPlugin);
1181 /* Tell everyone we depend on that we no longer exist */
1182 for (pl_iter = pPlugin->m_dependsOn.begin();
1183 pl_iter != pPlugin->m_dependsOn.end();
1186 pOther = (*pl_iter);
1187 pOther->m_dependents.remove(pPlugin);
1190 /* Remove all of our native functions */
1191 List<FakeNative *>::iterator fn_iter;
1192 FakeNative *pNative;
1193 for (fn_iter = pPlugin->m_fakeNatives.begin();
1194 fn_iter != pPlugin->m_fakeNatives.end();
1197 pNative = (*fn_iter);
1198 m_Natives.remove(pNative);
1199 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1200 g_pVM->DestroyFakeNative(pNative->func);
1204 List<IPluginsListener *>::iterator iter;
1205 IPluginsListener *pListener;
1207 if (pPlugin->GetStatus() <= Plugin_Error)
1209 /* Notify listeners of unloading */
1210 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1212 pListener = (*iter);
1213 pListener->OnPluginUnloaded(pPlugin);
1216 pPlugin->Call_OnPluginEnd();
1219 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1221 /* Notify listeners of destruction */
1222 pListener = (*iter);
1223 pListener->OnPluginDestroyed(pPlugin);
1226 /* Tell the plugin to delete itself */
1232 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1234 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1238 unsigned int CPluginManager::GetPluginCount()
1240 return m_plugins.size();
1243 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1245 m_listeners.push_back(listener);
1248 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1250 m_listeners.remove(listener);
1253 IPluginIterator *CPluginManager::GetPluginIterator()
1255 if (m_iters.empty())
1257 return new CPluginIterator(&m_plugins);
1259 CPluginIterator *iter = m_iters.front();
1266 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1271 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1273 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1274 size_t alias_len = 0;
1275 size_t local_len = 0;
1277 const char *ptr = alias;
1278 unsigned int alias_explicit_paths = 0;
1279 unsigned int alias_path_end = 0;
1280 while (*ptr != '\0')
1282 if (*ptr == '\\' || *ptr == '/')
1284 alias_explicit_paths++;
1285 alias_path_end = alias_len;
1291 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1293 /* Trailing slash is totally invalid here */
1298 unsigned int local_explicit_paths = 0;
1299 unsigned int local_path_end = 0;
1300 while (*ptr != '\0')
1302 if (*ptr == '\\' || *ptr == '/')
1304 local_explicit_paths++;
1305 local_path_end = local_len;
1311 /* If the alias has more explicit paths than the real path,
1312 * no match will be possible.
1314 if (alias_explicit_paths > local_explicit_paths)
1319 if (alias_explicit_paths)
1321 /* We need to find if the paths match now. For example, these should all match:
1323 * csdm optional/csdm
1324 * csdm/ban optional/crab/csdm/ban
1326 const char *aliasptr = alias;
1327 const char *localptr = localpath;
1331 if (*aliasptr != *localptr)
1333 /* We have to knock one path off */
1334 local_explicit_paths--;
1335 if (alias_explicit_paths > local_explicit_paths)
1337 /* Skip out if we're gonna have an impossible match */
1340 /* Eat up localptr tokens until we get a result */
1341 while (((localptr - localpath) < (int)local_path_end)
1343 && *localptr != '\\')
1347 /* Check if we hit the end of our searchable area.
1348 * This probably isn't possible because of the path
1349 * count check, but it's a good idea anyway.
1351 if ((localptr - localpath) >= (int)local_path_end)
1355 /* Consume the slash token */
1358 /* Reset the alias pointer so we can continue consuming */
1364 * This is safe because if localptr terminates early, aliasptr will too
1368 /* We should never reach the end of the string because of this check. */
1369 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1370 bool localend = (localptr - localpath) > (int)local_path_end;
1371 if (aliasend || localend)
1373 if (aliasend && localend)
1375 /* we matched, and we can break out now */
1379 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1384 /* If we got here, it's safe to compare the next two tokens */
1385 if (*localptr != *aliasptr)
1396 /* If we got here, it's time to compare filenames */
1397 const char *aliasptr = alias;
1398 const char *localptr = localpath;
1400 if (alias_explicit_paths)
1402 aliasptr = &alias[alias_path_end + 1];
1405 if (local_explicit_paths)
1407 localptr = &localpath[local_path_end + 1];
1412 if (*aliasptr == '*')
1414 /* First, see if this is the last character */
1415 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1417 /* If so, there's no need to match anything else */
1420 /* Otherwise, we need to search for an appropriate matching sequence in local.
1421 * Note that we only need to search up to the next asterisk.
1425 const char *local_orig = localptr;
1429 while (*aliasptr != '\0' && *aliasptr != '*')
1431 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1432 if (*aliasptr != *localptr)
1442 /* If we didn't get a match, we need to advance the search stream.
1443 * This will let us skip tokens while still searching for another match.
1445 localptr = ++local_orig;
1446 /* Make sure we don't go out of bounds */
1447 if (*localptr == '\0')
1458 /* If we got a match, move on to the next token */
1461 } else if (*aliasptr == '\0') {
1462 if (*localptr == '\0'
1464 strcmp(localptr, ".smx") == 0)
1470 } else if (*aliasptr != *localptr) {
1480 bool CPluginManager::IsLateLoadTime() const
1482 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1485 void CPluginManager::OnSourceModAllInitialized()
1487 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1490 g_HandleSys.InitAccessDefaults(NULL, &sec);
1492 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1493 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1495 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1496 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1498 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1500 g_ShareSys.AddInterface(NULL, this);
1503 void CPluginManager::OnSourceModShutdown()
1505 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1507 List<CPlugin *>::iterator iter;
1508 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1510 UnloadPlugin((*iter));
1513 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1514 g_ShareSys.DestroyIdentType(g_PluginIdent);
1515 g_ShareSys.DestroyIdentity(m_MyIdent);
1518 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1520 /* We don't care about the internal object, actually */
1523 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1525 m_natives.push_back(natives);
1528 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1536 sec.pIdentity = m_MyIdent;
1538 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1551 CPlugin *CPluginManager::GetPluginByOrder(int num)
1553 if (num < 1 || num > (int)GetPluginCount())
1561 IPluginIterator *iter = GetPluginIterator();
1562 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1564 pl = (CPlugin *)(iter->GetPlugin());
1570 const char *CPluginManager::GetStatusText(PluginStatus st)
1574 case Plugin_Running:
1580 case Plugin_Uncompiled:
1581 return "Uncompiled";
1582 case Plugin_BadLoad:
1592 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1596 const char *cmd = g_RootMenu.GetArgument(2);
1597 if (strcmp(cmd, "list") == 0)
1600 unsigned int id = 1;
1601 int plnum = GetPluginCount();
1605 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1608 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1611 IPluginIterator *iter = GetPluginIterator();
1612 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1614 IPlugin *pl = iter->GetPlugin();
1615 assert(pl->GetStatus() != Plugin_Created);
1617 const sm_plugininfo_t *info = pl->GetPublicInfo();
1618 if (pl->GetStatus() != Plugin_Running)
1620 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1622 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1624 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1625 if (IS_STR_FILLED(info->version))
1627 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1629 if (IS_STR_FILLED(info->author))
1631 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1633 g_RootMenu.ConsolePrint("%s", buffer);
1638 } else if (strcmp(cmd, "load") == 0) {
1641 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1647 const char *filename = g_RootMenu.GetArgument(3);
1648 IPlugin *pl = LoadPlugin(filename, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1652 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", filename);
1658 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", filename);
1660 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", filename, error);
1664 } else if (strcmp(cmd, "unload") == 0) {
1667 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1672 int num = atoi(g_RootMenu.GetArgument(3));
1673 if (num < 1 || num > (int)GetPluginCount())
1675 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1679 IPluginIterator *iter = GetPluginIterator();
1680 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1682 IPlugin *pl = iter->GetPlugin();
1684 char name[PLATFORM_MAX_PATH+1];
1685 const sm_plugininfo_t *info = pl->GetPublicInfo();
1686 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1688 if (UnloadPlugin(pl))
1690 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1692 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1697 } else if (strcmp(cmd, "info") == 0) {
1700 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1704 int num = atoi(g_RootMenu.GetArgument(3));
1705 if (num < 1 || num > (int)GetPluginCount())
1707 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1711 CPlugin *pl = GetPluginByOrder(num);
1712 const sm_plugininfo_t *info = pl->GetPublicInfo();
1714 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1715 if (pl->GetStatus() <= Plugin_Error)
1717 if (IS_STR_FILLED(info->name))
1719 if (IS_STR_FILLED(info->description))
1721 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1723 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1726 if (IS_STR_FILLED(info->author))
1728 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1730 if (IS_STR_FILLED(info->version))
1732 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1734 if (IS_STR_FILLED(info->url))
1736 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1738 if (pl->GetStatus() == Plugin_Error)
1740 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
1742 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "yes" : "no");
1743 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "yes" : "no");
1746 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
1747 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
1748 info->name ? info->name : "<none>",
1749 info->version ? info->version : "<none>");
1750 if (IS_STR_FILLED(info->url))
1752 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
1757 } else if (strcmp(cmd, "debug") == 0) {
1760 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
1764 int num = atoi(g_RootMenu.GetArgument(3));
1765 if (num < 1 || num > (int)GetPluginCount())
1767 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1772 const char *mode = g_RootMenu.GetArgument(4);
1773 if ((res=strcmp("on", mode)) && strcmp("off", mode))
1775 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
1787 CPlugin *pl = GetPluginByOrder(num);
1788 if (debug && pl->IsDebugging())
1790 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
1792 } else if (!debug && !pl->IsDebugging()) {
1793 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
1798 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
1800 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
1803 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
1804 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
1810 /* Draw the main menu */
1811 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
1812 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
1813 g_RootMenu.DrawGenericOption("load", "Load a plugin");
1814 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
1815 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
1816 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
1819 void CPluginManager::ReloadOrUnloadPlugins()
1821 List<CPlugin *>::iterator iter;
1822 List<CPlugin *> tmp_list = m_plugins;
1826 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
1829 if (pl->GetType() == PluginType_MapOnly)
1831 UnloadPlugin((IPlugin *)pl);
1832 } else if (pl->GetType() == PluginType_MapUpdated) {
1833 t = pl->GetFileTimeStamp();
1834 if (!t || t > pl->GetTimeStamp())
1836 pl->SetTimeStamp(t);
1837 UnloadPlugin((IPlugin *)pl);
1843 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
1845 List<IPluginsListener *>::iterator iter;
1846 IPluginsListener *pListener;
1847 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1849 pListener = (*iter);
1850 pListener->OnPluginPauseChange(pl, paused);
1854 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
1856 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
1861 FakeNative *pNative = new FakeNative;
1863 pNative->func = g_pVM->CreateFakeNative(func, pNative);
1870 pNative->call = pFunction;
1871 pNative->name.assign(name);
1872 pNative->ctx = pFunction->GetParentContext();
1874 m_Natives.push_back(pNative);
1875 sm_trie_insert(m_pNativeLookup, name,pNative);
1877 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
1878 pPlugin->m_fakeNatives.push_back(pNative);