3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
16 #include "PluginSys.h"
18 #include "LibrarySys.h"
19 #include "HandleSys.h"
20 #include "ForwardSys.h"
21 #include "sourcemm_api.h"
22 #include "sourcemod.h"
23 #include "TextParsers.h"
25 #include "ExtensionSys.h"
26 #include "sm_srvcmds.h"
27 #include "sm_stringutil.h"
29 CPluginManager g_PluginSys;
30 HandleType_t g_PluginType = 0;
31 IdentityType_t g_PluginIdent = 0;
33 CPlugin::CPlugin(const char *file)
35 static int MySerial = 0;
37 m_type = PluginType_Private;
38 m_status = Plugin_Uncompiled;
39 m_serial = ++MySerial;
41 m_errormsg[256] = '\0';
42 snprintf(m_filename, sizeof(m_filename), "%s", file);
45 m_pProps = sm_trie_create();
46 m_FakeNativesMissing = false;
54 sec.pOwner = g_PluginSys.GetIdentity();
55 sec.pIdentity = sec.pOwner;
57 g_HandleSys.FreeHandle(m_handle, &sec);
58 g_ShareSys.DestroyIdentity(m_ident);
68 m_ctx.vm->FreeContext(m_ctx.ctx);
73 m_ctx.vm->AbortCompilation(m_ctx.co);
79 g_pSourcePawn->FreeFromMemory(m_plugin);
84 sm_trie_destroy(m_pProps);
88 void CPlugin::InitIdentity()
92 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent);
93 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
94 m_ctx.base->SetIdentity(m_ident);
98 Handle_t CPlugin::GetMyHandle()
103 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
105 char fullpath[PLATFORM_MAX_PATH];
106 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
107 FILE *fp = fopen(fullpath, "rb");
109 CPlugin *pPlugin = new CPlugin(file);
115 snprintf(error, maxlength, "Unable to open file");
117 pPlugin->m_status = Plugin_BadLoad;
122 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
128 snprintf(error, maxlength, "Error %d while parsing plugin", err);
130 pPlugin->m_status = Plugin_BadLoad;
136 pPlugin->m_plugin = pl;
141 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
143 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
145 if (exists && remove)
147 sm_trie_delete(m_pProps, prop);
153 bool CPlugin::SetProperty(const char *prop, void *ptr)
155 return sm_trie_insert(m_pProps, prop, ptr);
158 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
165 /* :NOTICE: We will eventually need to change these natives
166 * for swapping in new contexts
168 if (m_ctx.co || m_ctx.ctx)
173 m_status = Plugin_Uncompiled;
176 m_ctx.co = vm->StartCompilation(m_plugin);
181 void CPlugin::CancelMyCompile()
188 m_ctx.vm->AbortCompilation(m_ctx.co);
193 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
201 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
204 memset(&m_ctx, 0, sizeof(m_ctx));
207 snprintf(error, maxlength, "JIT failed to compile (error %d)", err);
212 m_ctx.base = new BaseContext(m_ctx.ctx);
213 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
215 m_status = Plugin_Created;
223 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
225 PluginStatus old_status = m_status;
228 if (old_status == Plugin_Running)
230 /* Tell everyone we're now paused */
231 g_PluginSys._SetPauseState(this, true);
235 va_start(ap, error_fmt);
236 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
241 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
245 void CPlugin::UpdateInfo()
247 /* Now grab the info */
249 IPluginContext *base = GetBaseContext();
250 int err = base->FindPubvarByName("myinfo", &idx);
252 memset(&m_info, 0, sizeof(m_info));
254 if (err == SP_ERROR_NONE)
256 struct sm_plugininfo_c_t
264 sm_plugininfo_c_t *cinfo;
267 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
268 base->LocalToString(cinfo->name, (char **)&m_info.name);
269 base->LocalToString(cinfo->description, (char **)&m_info.description);
270 base->LocalToString(cinfo->author, (char **)&m_info.author);
271 base->LocalToString(cinfo->url, (char **)&m_info.url);
272 base->LocalToString(cinfo->version, (char **)&m_info.version);
275 m_info.author = m_info.author ? m_info.author : "";
276 m_info.description = m_info.description ? m_info.description : "";
277 m_info.name = m_info.name ? m_info.name : "";
278 m_info.url = m_info.url ? m_info.url : "";
279 m_info.version = m_info.version ? m_info.version : "";
282 void CPlugin::Call_OnPluginStart()
284 if (m_status != Plugin_Loaded)
289 m_status = Plugin_Running;
292 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
299 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
301 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
305 void CPlugin::Call_OnPluginEnd()
307 if (m_status > Plugin_Paused)
313 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
319 pFunction->Execute(&result);
322 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
324 if (m_status != Plugin_Created)
329 m_status = Plugin_Loaded;
333 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
340 pFunction->PushCell(m_handle);
341 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
342 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
343 pFunction->PushCell(maxlength);
344 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
349 if (!result || m_status != Plugin_Loaded)
357 const sp_plugin_t *CPlugin::GetPluginStructure()
362 IPluginContext *CPlugin::GetBaseContext()
367 sp_context_t *CPlugin::GetContext()
372 const char *CPlugin::GetFilename()
377 PluginType CPlugin::GetType()
382 const sm_plugininfo_t *CPlugin::GetPublicInfo()
387 unsigned int CPlugin::GetSerial()
392 PluginStatus CPlugin::GetStatus()
397 bool CPlugin::IsDebugging()
404 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
407 bool CPlugin::SetPauseState(bool paused)
409 if (paused && GetStatus() != Plugin_Paused)
412 } else if (!paused && GetStatus() != Plugin_Running) {
416 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
420 pFunction->PushCell(paused ? 1 : 0);
421 pFunction->Execute(&result);
426 m_status = Plugin_Paused;
427 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
429 m_status = Plugin_Running;
430 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
433 g_PluginSys._SetPauseState(this, paused);
438 IdentityToken_t *CPlugin::GetIdentity()
443 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
451 snprintf(error, maxlength, "Plugin is not runnable.");
456 if (debug && IsDebugging())
460 snprintf(error, maxlength, "Plugin is already in debug mode.");
463 } else if (!debug && !IsDebugging()) {
466 snprintf(error, maxlength, "Plugins is already in production mode.");
471 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
472 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
476 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
481 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
485 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
486 new_ctx->hp = m_ctx.ctx->hp;
487 new_ctx->sp = m_ctx.ctx->sp;
488 new_ctx->frm = m_ctx.ctx->frm;
489 new_ctx->dbreak = m_ctx.ctx->dbreak;
490 new_ctx->context = m_ctx.ctx->context;
491 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
493 uint32_t nativeCount = m_plugin->info.natives_num;
494 for (uint32_t i=0; i<nativeCount; i++)
496 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
497 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
500 g_pVM->FreeContext(m_ctx.ctx);
502 m_ctx.base->SetContext(new_ctx);
508 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
516 bool CPlugin::IsRunnable()
518 return (m_status <= Plugin_Paused) ? true : false;
521 time_t CPlugin::GetFileTimeStamp()
523 char path[PLATFORM_MAX_PATH];
524 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
525 #ifdef PLATFORM_WINDOWS
527 if (_stat(path, &s) != 0)
528 #elif defined PLATFORM_POSIX
530 if (stat(path, &s) != 0)
539 time_t CPlugin::GetTimeStamp()
544 void CPlugin::SetTimeStamp(time_t t)
549 void CPlugin::AddLangFile(unsigned int index)
551 m_PhraseFiles.push_back(index);
554 size_t CPlugin::GetLangFileCount()
556 return m_PhraseFiles.size();
559 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
561 return m_PhraseFiles.at(index);
564 void CPlugin::DependencyDropped(CPlugin *pOwner)
571 List<FakeNative *>::iterator iter;
575 unsigned int unbound = 0;
577 for (iter = pOwner->m_fakeNatives.begin();
578 iter != pOwner->m_fakeNatives.end();
582 /* Find this native! */
583 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
588 m_ctx.base->GetNativeByIndex(idx, &native);
590 native->status = SP_NATIVE_UNBOUND;
594 /* :IDEA: in the future, add native trapping? */
597 m_FakeNativesMissing = true;
598 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
601 m_dependsOn.remove(pOwner);
608 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
614 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
619 bool CPluginManager::CPluginIterator::MorePlugins()
621 return (current != mylist->end());
624 void CPluginManager::CPluginIterator::NextPlugin()
629 void CPluginManager::CPluginIterator::Release()
631 g_PluginSys.ReleaseIterator(this);
634 CPluginManager::CPluginIterator::~CPluginIterator()
638 void CPluginManager::CPluginIterator::Reset()
640 current = mylist->begin();
647 CPluginManager::CPluginManager()
649 m_LoadLookup = sm_trie_create();
650 m_AllPluginsLoaded = false;
652 m_pNativeLookup = sm_trie_create();
655 CPluginManager::~CPluginManager()
658 * Ignore the fact that there might be plugins in the cache.
659 * This usually means that Core is not being unloaded properly, and everything
660 * will crash anyway. YAY
662 sm_trie_destroy(m_LoadLookup);
663 sm_trie_destroy(m_pNativeLookup);
665 CStack<CPluginManager::CPluginIterator *>::iterator iter;
666 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
673 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
675 /* First read in the database of plugin settings */
677 unsigned int line, col;
678 m_AllPluginsLoaded = false;
679 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
681 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
682 const char *err_msg = g_TextParser.GetSMCErrorString(err);
685 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
689 LoadPluginsFromDir(basedir, NULL);
692 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
694 char base_path[PLATFORM_MAX_PATH];
696 /* Form the current path to start reading from */
697 if (localpath == NULL)
699 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
701 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
704 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
709 g_LibSys.GetPlatformError(error, sizeof(error));
710 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
711 g_Logger.LogError("[SM] Platform returned error: %s", error);
715 while (dir->MoreFiles())
717 if (dir->IsEntryDirectory()
718 && (strcmp(dir->GetEntryName(), ".") != 0)
719 && (strcmp(dir->GetEntryName(), "..") != 0)
720 && (strcmp(dir->GetEntryName(), "disabled") != 0)
721 && (strcmp(dir->GetEntryName(), "optional") != 0))
723 char new_local[PLATFORM_MAX_PATH];
724 if (localpath == NULL)
726 /* If no path yet, don't add a former slash */
727 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
729 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
731 LoadPluginsFromDir(basedir, new_local);
732 } else if (dir->IsEntryFile()) {
733 const char *name = dir->GetEntryName();
734 size_t len = strlen(name);
736 && strcmp(&name[len-4], ".smx") == 0)
738 /* If the filename matches, load the plugin */
739 char plugin[PLATFORM_MAX_PATH];
740 if (localpath == NULL)
742 snprintf(plugin, sizeof(plugin), "%s", name);
744 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
746 LoadAutoPlugin(plugin);
751 g_LibSys.CloseDirectory(dir);
754 //well i have discovered that gabe newell is very fat, so i wrote this comment now
755 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
758 * Does this plugin already exist?
761 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
763 /* Check to see if we should try reloading it */
764 if (pPlugin->GetStatus() == Plugin_BadLoad
765 || pPlugin->GetStatus() == Plugin_Error
766 || pPlugin->GetStatus() == Plugin_Failed)
768 UnloadPlugin(pPlugin);
774 return LoadRes_AlreadyLoaded;
778 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
780 assert(pPlugin != NULL);
782 pPlugin->m_type = PluginType_MapUpdated;
784 ICompilation *co = NULL;
786 if (pPlugin->m_status == Plugin_Uncompiled)
788 co = pPlugin->StartMyCompile(g_pVM);
791 PluginSettings *pset;
792 unsigned int setcount = m_PluginInfo.GetSettingsNum();
793 for (unsigned int i=0; i<setcount; i++)
795 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
799 pPlugin->m_type = pset->type_val;
802 for (unsigned int j=0; j<pset->opts_num; j++)
804 const char *key, *val;
805 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
810 if (!g_pVM->SetCompilationOption(co, key, val))
814 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
816 pPlugin->CancelMyCompile();
824 /* Do the actual compiling */
827 pPlugin->FinishMyCompile(error, maxlength);
832 if (pPlugin->GetStatus() == Plugin_Created)
834 AddCoreNativesToPlugin(pPlugin);
835 pPlugin->InitIdentity();
836 if (pPlugin->Call_AskPluginLoad(error, maxlength))
838 /* Autoload any modules */
839 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
843 /* Save the time stamp */
844 time_t t = pPlugin->GetFileTimeStamp();
845 pPlugin->SetTimeStamp(t);
852 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
855 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
861 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
867 if (res == LoadRes_AlreadyLoaded)
875 /* Run second pass if we need to */
876 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
878 if (!RunSecondPass(pl, error, maxlength))
888 void CPluginManager::LoadAutoPlugin(const char *plugin)
892 char error[255] = "Unknown error";
894 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
896 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
897 pl->SetErrorState(Plugin_Failed, "%s", error);
900 if (res == LoadRes_Successful)
906 void CPluginManager::AddPlugin(CPlugin *pPlugin)
908 List<IPluginsListener *>::iterator iter;
909 IPluginsListener *pListener;
911 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
914 pListener->OnPluginCreated(pPlugin);
917 m_plugins.push_back(pPlugin);
918 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
921 void CPluginManager::LoadAll_SecondPass()
923 List<CPlugin *>::iterator iter;
927 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
930 if (pPlugin->GetStatus() == Plugin_Loaded)
933 if (!RunSecondPass(pPlugin, error, sizeof(error)))
935 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
936 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
941 m_AllPluginsLoaded = true;
944 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
946 /* Find any extensions this plugin needs */
955 IPluginContext *pBase = pPlugin->GetBaseContext();
956 uint32_t num = pBase->GetPubVarsNum();
959 char path[PLATFORM_MAX_PATH];
961 for (uint32_t i=0; i<num; i++)
963 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
967 if (strncmp(pubvar->name, "__ext_", 6) == 0)
969 ext = (_ext *)pubvar->offs;
970 if (!ext->required && !ext->autoload)
974 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
978 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
984 /* Attempt to auto-load if necessary */
987 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
988 g_Extensions.LoadAutoExtension(path);
990 } else if (pass == 2) {
991 /* Is this required? */
994 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
995 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
997 pExt = g_Extensions.FindExtensionByName(name);
999 /* :TODO: should we bind to unloaded extensions?
1000 * Currently the extension manager will ignore this.
1002 if (!pExt || !pExt->IsRunning(NULL, 0))
1006 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1010 g_Extensions.BindChildPlugin(pExt, pPlugin);
1020 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1022 /* Second pass for extension requirements */
1023 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1028 /* Bind all extra natives */
1029 g_Extensions.BindAllNativesToPlugin(pPlugin);
1030 AddFakeNativesToPlugin(pPlugin);
1032 /* Find any unbound natives
1033 * Right now, these are not allowed
1035 IPluginContext *pContext = pPlugin->GetBaseContext();
1036 uint32_t num = pContext->GetNativesNum();
1037 sp_native_t *native;
1038 for (unsigned int i=0; i<num; i++)
1040 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1044 if (native->status == SP_NATIVE_UNBOUND
1045 && native->name[0] != '@')
1049 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1055 /* Finish by telling all listeners */
1056 List<IPluginsListener *>::iterator iter;
1057 IPluginsListener *pListener;
1058 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1060 pListener = (*iter);
1061 pListener->OnPluginLoaded(pPlugin);
1064 /* Tell this plugin to finish initializing itself */
1065 pPlugin->Call_OnPluginStart();
1067 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1068 if (pPlugin->GetStatus() >= Plugin_Paused && pPlugin->m_fakeNatives.size())
1070 List<CPlugin *>::iterator pl_iter;
1072 for (pl_iter = m_plugins.begin();
1073 pl_iter != m_plugins.end();
1076 pOther = (*pl_iter);
1077 if (pOther->GetStatus() == Plugin_Error
1078 && pOther->m_FakeNativesMissing)
1080 TryRefreshNatives(pOther);
1088 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1090 List<sp_nativeinfo_t *>::iterator iter;
1092 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1094 sp_nativeinfo_t *natives = (*iter);
1095 IPluginContext *ctx = pPlugin->GetBaseContext();
1097 /* Attempt to bind every native! */
1098 while (natives[i].func != NULL)
1100 ctx->BindNative(&natives[i++]);
1105 void CPluginManager::TryRefreshNatives(CPlugin *pPlugin)
1107 assert(pPlugin->GetBaseContext() != NULL);
1109 AddFakeNativesToPlugin(pPlugin);
1111 /* Find any unbound natives
1112 * Right now, these are not allowed
1114 IPluginContext *pContext = pPlugin->GetBaseContext();
1115 uint32_t num = pContext->GetNativesNum();
1116 sp_native_t *native;
1117 for (unsigned int i=0; i<num; i++)
1119 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1123 if (native->status == SP_NATIVE_UNBOUND)
1125 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1130 /* If we got here, all natives are okay again! */
1131 pPlugin->m_status = Plugin_Running;
1132 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1134 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1135 _SetPauseState(pPlugin, false);
1139 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1141 IPluginContext *pContext = pPlugin->GetBaseContext();
1142 sp_nativeinfo_t native;
1144 List<FakeNative *>::iterator iter;
1145 FakeNative *pNative;
1147 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1150 ctx = pNative->ctx->GetContext();
1151 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1153 /* Ignore natives in paused plugins */
1156 native.name = pNative->name.c_str();
1157 native.func = pNative->func;
1158 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1160 /* Add us as a dependency, but we're careful not to do this circularly! */
1161 if (pNative->ctx != pContext)
1163 CPlugin *pOther = GetPluginByCtx(ctx);
1164 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1166 pOther->m_dependents.push_back(pPlugin);
1168 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1170 pPlugin->m_dependsOn.push_back(pOther);
1177 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1179 CPlugin *pPlugin = (CPlugin *)plugin;
1181 /* This prevents removal during insertion or anything else weird */
1182 if (m_plugins.find(pPlugin) == m_plugins.end())
1187 /* Remove us from the lookup table and linked list */
1188 m_plugins.remove(pPlugin);
1189 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1191 /* Go through all dependent plugins and tell them this plugin is now gone */
1192 List<CPlugin *>::iterator pl_iter;
1194 for (pl_iter = pPlugin->m_dependents.begin();
1195 pl_iter != pPlugin->m_dependents.end();
1198 pOther = (*pl_iter);
1199 pOther->DependencyDropped(pPlugin);
1202 /* Tell everyone we depend on that we no longer exist */
1203 for (pl_iter = pPlugin->m_dependsOn.begin();
1204 pl_iter != pPlugin->m_dependsOn.end();
1207 pOther = (*pl_iter);
1208 pOther->m_dependents.remove(pPlugin);
1211 /* Remove all of our native functions */
1212 List<FakeNative *>::iterator fn_iter;
1213 FakeNative *pNative;
1214 for (fn_iter = pPlugin->m_fakeNatives.begin();
1215 fn_iter != pPlugin->m_fakeNatives.end();
1218 pNative = (*fn_iter);
1219 m_Natives.remove(pNative);
1220 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1221 g_pVM->DestroyFakeNative(pNative->func);
1225 List<IPluginsListener *>::iterator iter;
1226 IPluginsListener *pListener;
1228 if (pPlugin->GetStatus() <= Plugin_Error)
1230 /* Notify listeners of unloading */
1231 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1233 pListener = (*iter);
1234 pListener->OnPluginUnloaded(pPlugin);
1237 pPlugin->Call_OnPluginEnd();
1240 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1242 /* Notify listeners of destruction */
1243 pListener = (*iter);
1244 pListener->OnPluginDestroyed(pPlugin);
1247 /* Tell the plugin to delete itself */
1253 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1255 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1259 unsigned int CPluginManager::GetPluginCount()
1261 return m_plugins.size();
1264 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1266 m_listeners.push_back(listener);
1269 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1271 m_listeners.remove(listener);
1274 IPluginIterator *CPluginManager::GetPluginIterator()
1276 if (m_iters.empty())
1278 return new CPluginIterator(&m_plugins);
1280 CPluginIterator *iter = m_iters.front();
1287 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1292 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1294 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1295 size_t alias_len = 0;
1296 size_t local_len = 0;
1298 const char *ptr = alias;
1299 unsigned int alias_explicit_paths = 0;
1300 unsigned int alias_path_end = 0;
1301 while (*ptr != '\0')
1303 if (*ptr == '\\' || *ptr == '/')
1305 alias_explicit_paths++;
1306 alias_path_end = alias_len;
1312 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1314 /* Trailing slash is totally invalid here */
1319 unsigned int local_explicit_paths = 0;
1320 unsigned int local_path_end = 0;
1321 while (*ptr != '\0')
1323 if (*ptr == '\\' || *ptr == '/')
1325 local_explicit_paths++;
1326 local_path_end = local_len;
1332 /* If the alias has more explicit paths than the real path,
1333 * no match will be possible.
1335 if (alias_explicit_paths > local_explicit_paths)
1340 if (alias_explicit_paths)
1342 /* We need to find if the paths match now. For example, these should all match:
1344 * csdm optional/csdm
1345 * csdm/ban optional/crab/csdm/ban
1347 const char *aliasptr = alias;
1348 const char *localptr = localpath;
1352 if (*aliasptr != *localptr)
1354 /* We have to knock one path off */
1355 local_explicit_paths--;
1356 if (alias_explicit_paths > local_explicit_paths)
1358 /* Skip out if we're gonna have an impossible match */
1361 /* Eat up localptr tokens until we get a result */
1362 while (((localptr - localpath) < (int)local_path_end)
1364 && *localptr != '\\')
1368 /* Check if we hit the end of our searchable area.
1369 * This probably isn't possible because of the path
1370 * count check, but it's a good idea anyway.
1372 if ((localptr - localpath) >= (int)local_path_end)
1376 /* Consume the slash token */
1379 /* Reset the alias pointer so we can continue consuming */
1385 * This is safe because if localptr terminates early, aliasptr will too
1389 /* We should never reach the end of the string because of this check. */
1390 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1391 bool localend = (localptr - localpath) > (int)local_path_end;
1392 if (aliasend || localend)
1394 if (aliasend && localend)
1396 /* we matched, and we can break out now */
1400 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1405 /* If we got here, it's safe to compare the next two tokens */
1406 if (*localptr != *aliasptr)
1417 /* If we got here, it's time to compare filenames */
1418 const char *aliasptr = alias;
1419 const char *localptr = localpath;
1421 if (alias_explicit_paths)
1423 aliasptr = &alias[alias_path_end + 1];
1426 if (local_explicit_paths)
1428 localptr = &localpath[local_path_end + 1];
1433 if (*aliasptr == '*')
1435 /* First, see if this is the last character */
1436 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1438 /* If so, there's no need to match anything else */
1441 /* Otherwise, we need to search for an appropriate matching sequence in local.
1442 * Note that we only need to search up to the next asterisk.
1446 const char *local_orig = localptr;
1450 while (*aliasptr != '\0' && *aliasptr != '*')
1452 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1453 if (*aliasptr != *localptr)
1463 /* If we didn't get a match, we need to advance the search stream.
1464 * This will let us skip tokens while still searching for another match.
1466 localptr = ++local_orig;
1467 /* Make sure we don't go out of bounds */
1468 if (*localptr == '\0')
1479 /* If we got a match, move on to the next token */
1482 } else if (*aliasptr == '\0') {
1483 if (*localptr == '\0'
1485 strcmp(localptr, ".smx") == 0)
1491 } else if (*aliasptr != *localptr) {
1501 bool CPluginManager::IsLateLoadTime() const
1503 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1506 void CPluginManager::OnSourceModAllInitialized()
1508 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1511 g_HandleSys.InitAccessDefaults(NULL, &sec);
1513 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1514 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1516 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1517 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1519 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1521 g_ShareSys.AddInterface(NULL, this);
1524 void CPluginManager::OnSourceModShutdown()
1526 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1528 List<CPlugin *>::iterator iter;
1529 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1531 UnloadPlugin((*iter));
1534 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1535 g_ShareSys.DestroyIdentType(g_PluginIdent);
1536 g_ShareSys.DestroyIdentity(m_MyIdent);
1539 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1541 /* We don't care about the internal object, actually */
1544 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1546 m_natives.push_back(natives);
1549 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1557 sec.pIdentity = m_MyIdent;
1559 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1572 CPlugin *CPluginManager::GetPluginByOrder(int num)
1574 if (num < 1 || num > (int)GetPluginCount())
1582 IPluginIterator *iter = GetPluginIterator();
1583 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1585 pl = (CPlugin *)(iter->GetPlugin());
1591 const char *CPluginManager::GetStatusText(PluginStatus st)
1595 case Plugin_Running:
1601 case Plugin_Uncompiled:
1602 return "Uncompiled";
1603 case Plugin_BadLoad:
1613 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1617 const char *cmd = g_RootMenu.GetArgument(2);
1618 if (strcmp(cmd, "list") == 0)
1621 unsigned int id = 1;
1622 int plnum = GetPluginCount();
1626 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1629 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1632 IPluginIterator *iter = GetPluginIterator();
1633 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1635 IPlugin *pl = iter->GetPlugin();
1636 assert(pl->GetStatus() != Plugin_Created);
1638 const sm_plugininfo_t *info = pl->GetPublicInfo();
1639 if (pl->GetStatus() != Plugin_Running)
1641 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1643 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1645 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1646 if (IS_STR_FILLED(info->version))
1648 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1650 if (IS_STR_FILLED(info->author))
1652 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1654 g_RootMenu.ConsolePrint("%s", buffer);
1659 } else if (strcmp(cmd, "load") == 0) {
1662 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1668 const char *filename = g_RootMenu.GetArgument(3);
1670 char pluginfile[256];
1671 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1672 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1674 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1678 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1684 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1686 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
1690 } else if (strcmp(cmd, "unload") == 0) {
1693 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1698 int num = atoi(g_RootMenu.GetArgument(3));
1699 if (num < 1 || num > (int)GetPluginCount())
1701 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1705 IPluginIterator *iter = GetPluginIterator();
1706 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1708 IPlugin *pl = iter->GetPlugin();
1710 char name[PLATFORM_MAX_PATH];
1711 const sm_plugininfo_t *info = pl->GetPublicInfo();
1712 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1714 if (UnloadPlugin(pl))
1716 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1718 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1723 } else if (strcmp(cmd, "info") == 0) {
1726 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1730 int num = atoi(g_RootMenu.GetArgument(3));
1731 if (num < 1 || num > (int)GetPluginCount())
1733 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1737 CPlugin *pl = GetPluginByOrder(num);
1738 const sm_plugininfo_t *info = pl->GetPublicInfo();
1740 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1741 if (pl->GetStatus() <= Plugin_Error)
1743 if (IS_STR_FILLED(info->name))
1745 if (IS_STR_FILLED(info->description))
1747 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1749 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1752 if (IS_STR_FILLED(info->author))
1754 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1756 if (IS_STR_FILLED(info->version))
1758 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1760 if (IS_STR_FILLED(info->url))
1762 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1764 if (pl->GetStatus() == Plugin_Error)
1766 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
1768 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "yes" : "no");
1769 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "yes" : "no");
1772 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
1773 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
1774 info->name ? info->name : "<none>",
1775 info->version ? info->version : "<none>");
1776 if (IS_STR_FILLED(info->url))
1778 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
1783 } else if (strcmp(cmd, "debug") == 0) {
1786 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
1790 int num = atoi(g_RootMenu.GetArgument(3));
1791 if (num < 1 || num > (int)GetPluginCount())
1793 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1798 const char *mode = g_RootMenu.GetArgument(4);
1799 if ((res=strcmp("on", mode)) && strcmp("off", mode))
1801 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
1813 CPlugin *pl = GetPluginByOrder(num);
1814 if (debug && pl->IsDebugging())
1816 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
1818 } else if (!debug && !pl->IsDebugging()) {
1819 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
1824 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
1826 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
1829 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
1830 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
1836 /* Draw the main menu */
1837 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
1838 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
1839 g_RootMenu.DrawGenericOption("load", "Load a plugin");
1840 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
1841 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
1842 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
1845 void CPluginManager::ReloadOrUnloadPlugins()
1847 List<CPlugin *>::iterator iter;
1848 List<CPlugin *> tmp_list = m_plugins;
1852 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
1855 if (pl->GetType() == PluginType_MapOnly)
1857 UnloadPlugin((IPlugin *)pl);
1858 } else if (pl->GetType() == PluginType_MapUpdated) {
1859 t = pl->GetFileTimeStamp();
1860 if (!t || t > pl->GetTimeStamp())
1862 pl->SetTimeStamp(t);
1863 UnloadPlugin((IPlugin *)pl);
1869 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
1871 List<IPluginsListener *>::iterator iter;
1872 IPluginsListener *pListener;
1873 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1875 pListener = (*iter);
1876 pListener->OnPluginPauseChange(pl, paused);
1880 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
1882 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
1887 FakeNative *pNative = new FakeNative;
1889 pNative->func = g_pVM->CreateFakeNative(func, pNative);
1896 pNative->call = pFunction;
1897 pNative->name.assign(name);
1898 pNative->ctx = pFunction->GetParentContext();
1900 m_Natives.push_back(pNative);
1901 sm_trie_insert(m_pNativeLookup, name,pNative);
1903 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
1904 pPlugin->m_fakeNatives.push_back(pNative);
1909 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
1911 List<CPlugin *>::iterator iter;
1913 IPluginFunction *pFunction;
1915 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
1919 if (pPlugin->GetStatus() <= Plugin_Paused)
1921 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
1925 pForward->AddFunction(pFunction);