added sm_dump_handles command for tracking down Handle leaks... more to come someday
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"
28 #include "ConCmdManager.h"
29 #include "PlayerManager.h"
31 CPluginManager g_PluginSys;
32 HandleType_t g_PluginType = 0;
33 IdentityType_t g_PluginIdent = 0;
35 CPlugin::CPlugin(const char *file)
37 static int MySerial = 0;
39 m_type = PluginType_Private;
40 m_status = Plugin_Uncompiled;
41 m_serial = ++MySerial;
43 m_errormsg[256] = '\0';
44 snprintf(m_filename, sizeof(m_filename), "%s", file);
47 m_pProps = sm_trie_create();
48 m_FakeNativesMissing = false;
56 sec.pOwner = g_PluginSys.GetIdentity();
57 sec.pIdentity = sec.pOwner;
59 g_HandleSys.FreeHandle(m_handle, &sec);
60 g_ShareSys.DestroyIdentity(m_ident);
70 m_ctx.vm->FreeContext(m_ctx.ctx);
75 m_ctx.vm->AbortCompilation(m_ctx.co);
81 g_pSourcePawn->FreeFromMemory(m_plugin);
86 sm_trie_destroy(m_pProps);
90 void CPlugin::InitIdentity()
94 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
95 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
96 m_ctx.base->SetIdentity(m_ident);
100 Handle_t CPlugin::GetMyHandle()
105 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
107 char fullpath[PLATFORM_MAX_PATH];
108 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
109 FILE *fp = fopen(fullpath, "rb");
111 CPlugin *pPlugin = new CPlugin(file);
117 snprintf(error, maxlength, "Unable to open file");
119 pPlugin->m_status = Plugin_BadLoad;
124 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
130 snprintf(error, maxlength, "Error %d while parsing plugin", err);
132 pPlugin->m_status = Plugin_BadLoad;
138 pPlugin->m_plugin = pl;
143 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
145 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
147 if (exists && remove)
149 sm_trie_delete(m_pProps, prop);
155 bool CPlugin::SetProperty(const char *prop, void *ptr)
157 return sm_trie_insert(m_pProps, prop, ptr);
160 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
167 /* :NOTICE: We will eventually need to change these natives
168 * for swapping in new contexts
170 if (m_ctx.co || m_ctx.ctx)
175 m_status = Plugin_Uncompiled;
178 m_ctx.co = vm->StartCompilation(m_plugin);
183 void CPlugin::CancelMyCompile()
190 m_ctx.vm->AbortCompilation(m_ctx.co);
195 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
203 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
206 memset(&m_ctx, 0, sizeof(m_ctx));
209 snprintf(error, maxlength, "JIT failed to compile (error %d)", err);
214 m_ctx.base = new BaseContext(m_ctx.ctx);
215 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
217 m_status = Plugin_Created;
225 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
227 PluginStatus old_status = m_status;
230 if (old_status == Plugin_Running)
232 /* Tell everyone we're now paused */
233 g_PluginSys._SetPauseState(this, true);
237 va_start(ap, error_fmt);
238 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
243 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
247 void CPlugin::UpdateInfo()
249 /* Now grab the info */
251 IPluginContext *base = GetBaseContext();
252 int err = base->FindPubvarByName("myinfo", &idx);
254 memset(&m_info, 0, sizeof(m_info));
256 if (err == SP_ERROR_NONE)
258 struct sm_plugininfo_c_t
266 sm_plugininfo_c_t *cinfo;
269 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
270 base->LocalToString(cinfo->name, (char **)&m_info.name);
271 base->LocalToString(cinfo->description, (char **)&m_info.description);
272 base->LocalToString(cinfo->author, (char **)&m_info.author);
273 base->LocalToString(cinfo->url, (char **)&m_info.url);
274 base->LocalToString(cinfo->version, (char **)&m_info.version);
277 m_info.author = m_info.author ? m_info.author : "";
278 m_info.description = m_info.description ? m_info.description : "";
279 m_info.name = m_info.name ? m_info.name : "";
280 m_info.url = m_info.url ? m_info.url : "";
281 m_info.version = m_info.version ? m_info.version : "";
284 void CPlugin::Call_OnPluginStart()
286 if (m_status != Plugin_Loaded)
291 m_status = Plugin_Running;
294 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
301 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
303 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
307 if ((pFunction = m_ctx.base->GetFunctionByName("OnMapStart")) != NULL)
309 pFunction->Execute(NULL);
312 if (g_ConCmds.IsServerCfgDone())
314 if ((pFunction = m_ctx.base->GetFunctionByName("OnServerCfg")) != NULL)
316 pFunction->Execute(NULL);
322 void CPlugin::Call_OnPluginEnd()
324 if (m_status > Plugin_Paused)
330 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
336 pFunction->Execute(&result);
339 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
341 if (m_status != Plugin_Created)
346 m_status = Plugin_Loaded;
350 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
357 pFunction->PushCell(m_handle);
358 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
359 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
360 pFunction->PushCell(maxlength);
361 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
366 if (!result || m_status != Plugin_Loaded)
374 const sp_plugin_t *CPlugin::GetPluginStructure()
379 IPluginContext *CPlugin::GetBaseContext()
384 sp_context_t *CPlugin::GetContext()
389 const char *CPlugin::GetFilename()
394 PluginType CPlugin::GetType()
399 const sm_plugininfo_t *CPlugin::GetPublicInfo()
404 unsigned int CPlugin::GetSerial()
409 PluginStatus CPlugin::GetStatus()
414 bool CPlugin::IsDebugging()
421 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
424 bool CPlugin::SetPauseState(bool paused)
426 if (paused && GetStatus() != Plugin_Paused)
429 } else if (!paused && GetStatus() != Plugin_Running) {
433 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
437 pFunction->PushCell(paused ? 1 : 0);
438 pFunction->Execute(&result);
443 m_status = Plugin_Paused;
444 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
446 m_status = Plugin_Running;
447 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
450 g_PluginSys._SetPauseState(this, paused);
455 IdentityToken_t *CPlugin::GetIdentity()
460 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
468 snprintf(error, maxlength, "Plugin is not runnable.");
473 if (debug && IsDebugging())
477 snprintf(error, maxlength, "Plugin is already in debug mode.");
480 } else if (!debug && !IsDebugging()) {
483 snprintf(error, maxlength, "Plugins is already in production mode.");
488 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
489 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
493 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
498 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
502 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
503 new_ctx->hp = m_ctx.ctx->hp;
504 new_ctx->sp = m_ctx.ctx->sp;
505 new_ctx->frm = m_ctx.ctx->frm;
506 new_ctx->dbreak = m_ctx.ctx->dbreak;
507 new_ctx->context = m_ctx.ctx->context;
508 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
510 uint32_t nativeCount = m_plugin->info.natives_num;
511 for (uint32_t i=0; i<nativeCount; i++)
513 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
514 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
517 g_pVM->FreeContext(m_ctx.ctx);
519 m_ctx.base->SetContext(new_ctx);
525 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
533 bool CPlugin::IsRunnable()
535 return (m_status <= Plugin_Paused) ? true : false;
538 time_t CPlugin::GetFileTimeStamp()
540 char path[PLATFORM_MAX_PATH];
541 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
542 #ifdef PLATFORM_WINDOWS
544 if (_stat(path, &s) != 0)
545 #elif defined PLATFORM_POSIX
547 if (stat(path, &s) != 0)
556 time_t CPlugin::GetTimeStamp()
561 void CPlugin::SetTimeStamp(time_t t)
566 void CPlugin::AddLangFile(unsigned int index)
568 m_PhraseFiles.push_back(index);
571 size_t CPlugin::GetLangFileCount()
573 return m_PhraseFiles.size();
576 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
578 return m_PhraseFiles.at(index);
581 void CPlugin::DependencyDropped(CPlugin *pOwner)
588 List<FakeNative *>::iterator iter;
592 unsigned int unbound = 0;
594 for (iter = pOwner->m_fakeNatives.begin();
595 iter != pOwner->m_fakeNatives.end();
599 /* Find this native! */
600 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
605 m_ctx.base->GetNativeByIndex(idx, &native);
607 native->status = SP_NATIVE_UNBOUND;
611 /* :IDEA: in the future, add native trapping? */
614 m_FakeNativesMissing = true;
615 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
618 m_dependsOn.remove(pOwner);
625 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
631 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
636 bool CPluginManager::CPluginIterator::MorePlugins()
638 return (current != mylist->end());
641 void CPluginManager::CPluginIterator::NextPlugin()
646 void CPluginManager::CPluginIterator::Release()
648 g_PluginSys.ReleaseIterator(this);
651 CPluginManager::CPluginIterator::~CPluginIterator()
655 void CPluginManager::CPluginIterator::Reset()
657 current = mylist->begin();
664 CPluginManager::CPluginManager()
666 m_LoadLookup = sm_trie_create();
667 m_AllPluginsLoaded = false;
669 m_pNativeLookup = sm_trie_create();
672 CPluginManager::~CPluginManager()
675 * Ignore the fact that there might be plugins in the cache.
676 * This usually means that Core is not being unloaded properly, and everything
677 * will crash anyway. YAY
679 sm_trie_destroy(m_LoadLookup);
680 sm_trie_destroy(m_pNativeLookup);
682 CStack<CPluginManager::CPluginIterator *>::iterator iter;
683 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
690 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
692 /* First read in the database of plugin settings */
694 unsigned int line, col;
695 m_AllPluginsLoaded = false;
696 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
698 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
699 const char *err_msg = g_TextParser.GetSMCErrorString(err);
702 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
706 LoadPluginsFromDir(basedir, NULL);
709 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
711 char base_path[PLATFORM_MAX_PATH];
713 /* Form the current path to start reading from */
714 if (localpath == NULL)
716 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
718 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
721 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
726 g_LibSys.GetPlatformError(error, sizeof(error));
727 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
728 g_Logger.LogError("[SM] Platform returned error: %s", error);
732 while (dir->MoreFiles())
734 if (dir->IsEntryDirectory()
735 && (strcmp(dir->GetEntryName(), ".") != 0)
736 && (strcmp(dir->GetEntryName(), "..") != 0)
737 && (strcmp(dir->GetEntryName(), "disabled") != 0)
738 && (strcmp(dir->GetEntryName(), "optional") != 0))
740 char new_local[PLATFORM_MAX_PATH];
741 if (localpath == NULL)
743 /* If no path yet, don't add a former slash */
744 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
746 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
748 LoadPluginsFromDir(basedir, new_local);
749 } else if (dir->IsEntryFile()) {
750 const char *name = dir->GetEntryName();
751 size_t len = strlen(name);
753 && strcmp(&name[len-4], ".smx") == 0)
755 /* If the filename matches, load the plugin */
756 char plugin[PLATFORM_MAX_PATH];
757 if (localpath == NULL)
759 snprintf(plugin, sizeof(plugin), "%s", name);
761 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
763 LoadAutoPlugin(plugin);
768 g_LibSys.CloseDirectory(dir);
771 //well i have discovered that gabe newell is very fat, so i wrote this comment now
772 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
775 * Does this plugin already exist?
778 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
780 /* Check to see if we should try reloading it */
781 if (pPlugin->GetStatus() == Plugin_BadLoad
782 || pPlugin->GetStatus() == Plugin_Error
783 || pPlugin->GetStatus() == Plugin_Failed)
785 UnloadPlugin(pPlugin);
791 return LoadRes_AlreadyLoaded;
795 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
797 assert(pPlugin != NULL);
799 pPlugin->m_type = PluginType_MapUpdated;
801 ICompilation *co = NULL;
803 if (pPlugin->m_status == Plugin_Uncompiled)
805 co = pPlugin->StartMyCompile(g_pVM);
808 PluginSettings *pset;
809 unsigned int setcount = m_PluginInfo.GetSettingsNum();
810 for (unsigned int i=0; i<setcount; i++)
812 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
816 pPlugin->m_type = pset->type_val;
819 for (unsigned int j=0; j<pset->opts_num; j++)
821 const char *key, *val;
822 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
827 if (!g_pVM->SetCompilationOption(co, key, val))
831 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
833 pPlugin->CancelMyCompile();
841 /* Do the actual compiling */
844 pPlugin->FinishMyCompile(error, maxlength);
849 if (pPlugin->GetStatus() == Plugin_Created)
851 AddCoreNativesToPlugin(pPlugin);
852 pPlugin->InitIdentity();
853 if (pPlugin->Call_AskPluginLoad(error, maxlength))
855 /* Autoload any modules */
856 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
860 /* Save the time stamp */
861 time_t t = pPlugin->GetFileTimeStamp();
862 pPlugin->SetTimeStamp(t);
869 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
872 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
878 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
884 if (res == LoadRes_AlreadyLoaded)
892 /* Run second pass if we need to */
893 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
895 if (!RunSecondPass(pl, error, maxlength))
905 void CPluginManager::LoadAutoPlugin(const char *plugin)
909 char error[255] = "Unknown error";
911 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
913 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
914 pl->SetErrorState(Plugin_Failed, "%s", error);
917 if (res == LoadRes_Successful)
923 void CPluginManager::AddPlugin(CPlugin *pPlugin)
925 List<IPluginsListener *>::iterator iter;
926 IPluginsListener *pListener;
928 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
931 pListener->OnPluginCreated(pPlugin);
934 m_plugins.push_back(pPlugin);
935 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
938 void CPluginManager::LoadAll_SecondPass()
940 List<CPlugin *>::iterator iter;
944 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
947 if (pPlugin->GetStatus() == Plugin_Loaded)
950 if (!RunSecondPass(pPlugin, error, sizeof(error)))
952 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
953 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
958 m_AllPluginsLoaded = true;
961 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
963 /* Find any extensions this plugin needs */
972 IPluginContext *pBase = pPlugin->GetBaseContext();
973 uint32_t num = pBase->GetPubVarsNum();
976 char path[PLATFORM_MAX_PATH];
978 for (uint32_t i=0; i<num; i++)
980 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
984 if (strncmp(pubvar->name, "__ext_", 6) == 0)
986 ext = (_ext *)pubvar->offs;
987 if (!ext->required && !ext->autoload)
991 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
995 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1001 /* Attempt to auto-load if necessary */
1004 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1005 g_Extensions.LoadAutoExtension(path);
1007 } else if (pass == 2) {
1008 /* Is this required? */
1011 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1012 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1014 pExt = g_Extensions.FindExtensionByName(name);
1016 /* :TODO: should we bind to unloaded extensions?
1017 * Currently the extension manager will ignore this.
1019 if (!pExt || !pExt->IsRunning(NULL, 0))
1023 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1027 g_Extensions.BindChildPlugin(pExt, pPlugin);
1037 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1039 /* Second pass for extension requirements */
1040 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1045 /* Bind all extra natives */
1046 g_Extensions.BindAllNativesToPlugin(pPlugin);
1047 AddFakeNativesToPlugin(pPlugin);
1049 /* Find any unbound natives
1050 * Right now, these are not allowed
1052 IPluginContext *pContext = pPlugin->GetBaseContext();
1053 uint32_t num = pContext->GetNativesNum();
1054 sp_native_t *native;
1055 for (unsigned int i=0; i<num; i++)
1057 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1061 if (native->status == SP_NATIVE_UNBOUND
1062 && native->name[0] != '@')
1066 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1072 /* Finish by telling all listeners */
1073 List<IPluginsListener *>::iterator iter;
1074 IPluginsListener *pListener;
1075 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1077 pListener = (*iter);
1078 pListener->OnPluginLoaded(pPlugin);
1081 /* Tell this plugin to finish initializing itself */
1082 pPlugin->Call_OnPluginStart();
1084 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1085 if (pPlugin->GetStatus() >= Plugin_Paused && pPlugin->m_fakeNatives.size())
1087 List<CPlugin *>::iterator pl_iter;
1089 for (pl_iter = m_plugins.begin();
1090 pl_iter != m_plugins.end();
1093 pOther = (*pl_iter);
1094 if (pOther->GetStatus() == Plugin_Error
1095 && pOther->m_FakeNativesMissing)
1097 TryRefreshNatives(pOther);
1105 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1107 List<sp_nativeinfo_t *>::iterator iter;
1109 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1111 sp_nativeinfo_t *natives = (*iter);
1112 IPluginContext *ctx = pPlugin->GetBaseContext();
1114 /* Attempt to bind every native! */
1115 while (natives[i].func != NULL)
1117 ctx->BindNative(&natives[i++]);
1122 void CPluginManager::TryRefreshNatives(CPlugin *pPlugin)
1124 assert(pPlugin->GetBaseContext() != NULL);
1126 AddFakeNativesToPlugin(pPlugin);
1128 /* Find any unbound natives
1129 * Right now, these are not allowed
1131 IPluginContext *pContext = pPlugin->GetBaseContext();
1132 uint32_t num = pContext->GetNativesNum();
1133 sp_native_t *native;
1134 for (unsigned int i=0; i<num; i++)
1136 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1140 if (native->status == SP_NATIVE_UNBOUND)
1142 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1147 /* If we got here, all natives are okay again! */
1148 pPlugin->m_status = Plugin_Running;
1149 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1151 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1152 _SetPauseState(pPlugin, false);
1156 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1158 IPluginContext *pContext = pPlugin->GetBaseContext();
1159 sp_nativeinfo_t native;
1161 List<FakeNative *>::iterator iter;
1162 FakeNative *pNative;
1164 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1167 ctx = pNative->ctx->GetContext();
1168 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1170 /* Ignore natives in paused plugins */
1173 native.name = pNative->name.c_str();
1174 native.func = pNative->func;
1175 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1177 /* Add us as a dependency, but we're careful not to do this circularly! */
1178 if (pNative->ctx != pContext)
1180 CPlugin *pOther = GetPluginByCtx(ctx);
1181 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1183 pOther->m_dependents.push_back(pPlugin);
1185 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1187 pPlugin->m_dependsOn.push_back(pOther);
1194 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1196 CPlugin *pPlugin = (CPlugin *)plugin;
1198 /* This prevents removal during insertion or anything else weird */
1199 if (m_plugins.find(pPlugin) == m_plugins.end())
1204 /* Remove us from the lookup table and linked list */
1205 m_plugins.remove(pPlugin);
1206 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1208 /* Go through all dependent plugins and tell them this plugin is now gone */
1209 List<CPlugin *>::iterator pl_iter;
1211 for (pl_iter = pPlugin->m_dependents.begin();
1212 pl_iter != pPlugin->m_dependents.end();
1215 pOther = (*pl_iter);
1216 pOther->DependencyDropped(pPlugin);
1219 /* Tell everyone we depend on that we no longer exist */
1220 for (pl_iter = pPlugin->m_dependsOn.begin();
1221 pl_iter != pPlugin->m_dependsOn.end();
1224 pOther = (*pl_iter);
1225 pOther->m_dependents.remove(pPlugin);
1228 /* Remove all of our native functions */
1229 List<FakeNative *>::iterator fn_iter;
1230 FakeNative *pNative;
1231 for (fn_iter = pPlugin->m_fakeNatives.begin();
1232 fn_iter != pPlugin->m_fakeNatives.end();
1235 pNative = (*fn_iter);
1236 m_Natives.remove(pNative);
1237 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1238 g_pVM->DestroyFakeNative(pNative->func);
1242 List<IPluginsListener *>::iterator iter;
1243 IPluginsListener *pListener;
1245 if (pPlugin->GetStatus() <= Plugin_Error)
1247 /* Notify listeners of unloading */
1248 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1250 pListener = (*iter);
1251 pListener->OnPluginUnloaded(pPlugin);
1254 pPlugin->Call_OnPluginEnd();
1257 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1259 /* Notify listeners of destruction */
1260 pListener = (*iter);
1261 pListener->OnPluginDestroyed(pPlugin);
1264 /* Tell the plugin to delete itself */
1270 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1272 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1276 unsigned int CPluginManager::GetPluginCount()
1278 return m_plugins.size();
1281 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1283 m_listeners.push_back(listener);
1286 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1288 m_listeners.remove(listener);
1291 IPluginIterator *CPluginManager::GetPluginIterator()
1293 if (m_iters.empty())
1295 return new CPluginIterator(&m_plugins);
1297 CPluginIterator *iter = m_iters.front();
1304 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1309 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1311 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1312 size_t alias_len = 0;
1313 size_t local_len = 0;
1315 const char *ptr = alias;
1316 unsigned int alias_explicit_paths = 0;
1317 unsigned int alias_path_end = 0;
1318 while (*ptr != '\0')
1320 if (*ptr == '\\' || *ptr == '/')
1322 alias_explicit_paths++;
1323 alias_path_end = alias_len;
1329 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1331 /* Trailing slash is totally invalid here */
1336 unsigned int local_explicit_paths = 0;
1337 unsigned int local_path_end = 0;
1338 while (*ptr != '\0')
1340 if (*ptr == '\\' || *ptr == '/')
1342 local_explicit_paths++;
1343 local_path_end = local_len;
1349 /* If the alias has more explicit paths than the real path,
1350 * no match will be possible.
1352 if (alias_explicit_paths > local_explicit_paths)
1357 if (alias_explicit_paths)
1359 /* We need to find if the paths match now. For example, these should all match:
1361 * csdm optional/csdm
1362 * csdm/ban optional/crab/csdm/ban
1364 const char *aliasptr = alias;
1365 const char *localptr = localpath;
1369 if (*aliasptr != *localptr)
1371 /* We have to knock one path off */
1372 local_explicit_paths--;
1373 if (alias_explicit_paths > local_explicit_paths)
1375 /* Skip out if we're gonna have an impossible match */
1378 /* Eat up localptr tokens until we get a result */
1379 while (((localptr - localpath) < (int)local_path_end)
1381 && *localptr != '\\')
1385 /* Check if we hit the end of our searchable area.
1386 * This probably isn't possible because of the path
1387 * count check, but it's a good idea anyway.
1389 if ((localptr - localpath) >= (int)local_path_end)
1393 /* Consume the slash token */
1396 /* Reset the alias pointer so we can continue consuming */
1402 * This is safe because if localptr terminates early, aliasptr will too
1406 /* We should never reach the end of the string because of this check. */
1407 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1408 bool localend = (localptr - localpath) > (int)local_path_end;
1409 if (aliasend || localend)
1411 if (aliasend && localend)
1413 /* we matched, and we can break out now */
1417 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1422 /* If we got here, it's safe to compare the next two tokens */
1423 if (*localptr != *aliasptr)
1434 /* If we got here, it's time to compare filenames */
1435 const char *aliasptr = alias;
1436 const char *localptr = localpath;
1438 if (alias_explicit_paths)
1440 aliasptr = &alias[alias_path_end + 1];
1443 if (local_explicit_paths)
1445 localptr = &localpath[local_path_end + 1];
1450 if (*aliasptr == '*')
1452 /* First, see if this is the last character */
1453 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1455 /* If so, there's no need to match anything else */
1458 /* Otherwise, we need to search for an appropriate matching sequence in local.
1459 * Note that we only need to search up to the next asterisk.
1463 const char *local_orig = localptr;
1467 while (*aliasptr != '\0' && *aliasptr != '*')
1469 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1470 if (*aliasptr != *localptr)
1480 /* If we didn't get a match, we need to advance the search stream.
1481 * This will let us skip tokens while still searching for another match.
1483 localptr = ++local_orig;
1484 /* Make sure we don't go out of bounds */
1485 if (*localptr == '\0')
1496 /* If we got a match, move on to the next token */
1499 } else if (*aliasptr == '\0') {
1500 if (*localptr == '\0'
1502 strcmp(localptr, ".smx") == 0)
1508 } else if (*aliasptr != *localptr) {
1518 bool CPluginManager::IsLateLoadTime() const
1520 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1523 void CPluginManager::OnSourceModAllInitialized()
1525 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1528 g_HandleSys.InitAccessDefaults(NULL, &sec);
1530 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1531 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1533 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1534 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1536 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1538 g_ShareSys.AddInterface(NULL, this);
1541 void CPluginManager::OnSourceModShutdown()
1543 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1545 List<CPlugin *>::iterator iter;
1546 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1548 UnloadPlugin((*iter));
1551 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1552 g_ShareSys.DestroyIdentType(g_PluginIdent);
1553 g_ShareSys.DestroyIdentity(m_MyIdent);
1556 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1558 /* We don't care about the internal object, actually */
1561 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1563 m_natives.push_back(natives);
1566 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1574 sec.pIdentity = m_MyIdent;
1576 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1589 CPlugin *CPluginManager::GetPluginByOrder(int num)
1591 if (num < 1 || num > (int)GetPluginCount())
1599 IPluginIterator *iter = GetPluginIterator();
1600 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1602 pl = (CPlugin *)(iter->GetPlugin());
1608 const char *CPluginManager::GetStatusText(PluginStatus st)
1612 case Plugin_Running:
1618 case Plugin_Uncompiled:
1619 return "Uncompiled";
1620 case Plugin_BadLoad:
1630 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1634 const char *cmd = g_RootMenu.GetArgument(2);
1635 if (strcmp(cmd, "list") == 0)
1638 unsigned int id = 1;
1639 int plnum = GetPluginCount();
1643 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1646 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1649 IPluginIterator *iter = GetPluginIterator();
1650 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1652 IPlugin *pl = iter->GetPlugin();
1653 assert(pl->GetStatus() != Plugin_Created);
1655 const sm_plugininfo_t *info = pl->GetPublicInfo();
1656 if (pl->GetStatus() != Plugin_Running)
1658 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1660 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1662 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1663 if (IS_STR_FILLED(info->version))
1665 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1667 if (IS_STR_FILLED(info->author))
1669 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1671 g_RootMenu.ConsolePrint("%s", buffer);
1676 } else if (strcmp(cmd, "load") == 0) {
1679 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1685 const char *filename = g_RootMenu.GetArgument(3);
1687 char pluginfile[256];
1688 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1689 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1691 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1695 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1701 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1703 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
1707 } else if (strcmp(cmd, "unload") == 0) {
1710 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1715 int num = atoi(g_RootMenu.GetArgument(3));
1716 if (num < 1 || num > (int)GetPluginCount())
1718 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1722 IPluginIterator *iter = GetPluginIterator();
1723 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1725 IPlugin *pl = iter->GetPlugin();
1727 char name[PLATFORM_MAX_PATH];
1728 const sm_plugininfo_t *info = pl->GetPublicInfo();
1729 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1731 if (UnloadPlugin(pl))
1733 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1735 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1740 } else if (strcmp(cmd, "info") == 0) {
1743 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1747 int num = atoi(g_RootMenu.GetArgument(3));
1748 if (num < 1 || num > (int)GetPluginCount())
1750 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1754 CPlugin *pl = GetPluginByOrder(num);
1755 const sm_plugininfo_t *info = pl->GetPublicInfo();
1757 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1758 if (pl->GetStatus() <= Plugin_Error)
1760 if (IS_STR_FILLED(info->name))
1762 if (IS_STR_FILLED(info->description))
1764 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1766 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1769 if (IS_STR_FILLED(info->author))
1771 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1773 if (IS_STR_FILLED(info->version))
1775 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1777 if (IS_STR_FILLED(info->url))
1779 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1781 if (pl->GetStatus() == Plugin_Error)
1783 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
1785 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
1786 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
1788 const char *typestr = "";
1789 switch (pl->GetType())
1791 case PluginType_MapUpdated:
1792 typestr = "Map Change if Updated";
1794 case PluginType_MapOnly:
1795 typestr = "Map Change";
1797 case PluginType_Private:
1798 case PluginType_Global:
1803 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
1806 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
1807 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
1808 info->name ? info->name : "<none>",
1809 info->version ? info->version : "<none>");
1810 if (IS_STR_FILLED(info->url))
1812 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
1817 } else if (strcmp(cmd, "debug") == 0) {
1820 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
1824 int num = atoi(g_RootMenu.GetArgument(3));
1825 if (num < 1 || num > (int)GetPluginCount())
1827 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1832 const char *mode = g_RootMenu.GetArgument(4);
1833 if ((res=strcmp("on", mode)) && strcmp("off", mode))
1835 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
1847 CPlugin *pl = GetPluginByOrder(num);
1848 if (debug && pl->IsDebugging())
1850 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
1852 } else if (!debug && !pl->IsDebugging()) {
1853 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
1858 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
1860 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
1863 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
1864 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
1870 /* Draw the main menu */
1871 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
1872 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
1873 g_RootMenu.DrawGenericOption("load", "Load a plugin");
1874 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
1875 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
1876 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
1879 void CPluginManager::ReloadOrUnloadPlugins()
1881 List<CPlugin *>::iterator iter;
1882 List<CPlugin *> tmp_list = m_plugins;
1886 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
1889 if (pl->GetType() == PluginType_MapOnly)
1891 UnloadPlugin((IPlugin *)pl);
1892 } else if (pl->GetType() == PluginType_MapUpdated) {
1893 t = pl->GetFileTimeStamp();
1894 if (!t || t > pl->GetTimeStamp())
1896 pl->SetTimeStamp(t);
1897 UnloadPlugin((IPlugin *)pl);
1903 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
1905 List<IPluginsListener *>::iterator iter;
1906 IPluginsListener *pListener;
1907 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1909 pListener = (*iter);
1910 pListener->OnPluginPauseChange(pl, paused);
1914 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
1916 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
1921 FakeNative *pNative = new FakeNative;
1923 pNative->func = g_pVM->CreateFakeNative(func, pNative);
1930 pNative->call = pFunction;
1931 pNative->name.assign(name);
1932 pNative->ctx = pFunction->GetParentContext();
1934 m_Natives.push_back(pNative);
1935 sm_trie_insert(m_pNativeLookup, name,pNative);
1937 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
1938 pPlugin->m_fakeNatives.push_back(pNative);
1943 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
1945 List<CPlugin *>::iterator iter;
1947 IPluginFunction *pFunction;
1949 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
1953 if (pPlugin->GetStatus() <= Plugin_Paused)
1955 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
1959 pForward->AddFunction(pFunction);
1965 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
1967 if (pToken->type != g_PluginIdent)
1972 return (CPlugin *)(pToken->ptr);