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, "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");
298 pFunction->Execute(&result);
301 void CPlugin::Call_OnPluginEnd()
303 if (m_status > Plugin_Paused)
309 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
315 pFunction->Execute(&result);
318 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
320 if (m_status != Plugin_Created)
325 m_status = Plugin_Loaded;
329 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
336 pFunction->PushCell(m_handle);
337 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
338 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
339 pFunction->PushCell(maxlength);
340 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
345 if (!result || m_status != Plugin_Loaded)
353 const sp_plugin_t *CPlugin::GetPluginStructure()
358 IPluginContext *CPlugin::GetBaseContext()
363 sp_context_t *CPlugin::GetContext()
368 const char *CPlugin::GetFilename()
373 PluginType CPlugin::GetType()
378 const sm_plugininfo_t *CPlugin::GetPublicInfo()
383 unsigned int CPlugin::GetSerial()
388 PluginStatus CPlugin::GetStatus()
393 bool CPlugin::IsDebugging()
400 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
403 bool CPlugin::SetPauseState(bool paused)
405 if (paused && GetStatus() != Plugin_Paused)
408 } else if (!paused && GetStatus() != Plugin_Running) {
412 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
416 pFunction->PushCell(paused ? 1 : 0);
417 pFunction->Execute(&result);
422 m_status = Plugin_Paused;
423 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
425 m_status = Plugin_Running;
426 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
429 g_PluginSys._SetPauseState(this, paused);
434 IdentityToken_t *CPlugin::GetIdentity()
439 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
447 snprintf(error, maxlength, "Plugin is not runnable.");
452 if (debug && IsDebugging())
456 snprintf(error, maxlength, "Plugin is already in debug mode.");
459 } else if (!debug && !IsDebugging()) {
462 snprintf(error, maxlength, "Plugins is already in production mode.");
467 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
468 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
472 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
477 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
481 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
482 new_ctx->hp = m_ctx.ctx->hp;
483 new_ctx->sp = m_ctx.ctx->sp;
484 new_ctx->frm = m_ctx.ctx->frm;
485 new_ctx->dbreak = m_ctx.ctx->dbreak;
486 new_ctx->context = m_ctx.ctx->context;
487 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
489 uint32_t nativeCount = m_plugin->info.natives_num;
490 for (uint32_t i=0; i<nativeCount; i++)
492 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
493 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
496 g_pVM->FreeContext(m_ctx.ctx);
498 m_ctx.base->SetContext(new_ctx);
504 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
512 bool CPlugin::IsRunnable()
514 return (m_status <= Plugin_Paused) ? true : false;
517 time_t CPlugin::GetFileTimeStamp()
519 char path[PLATFORM_MAX_PATH];
520 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
521 #ifdef PLATFORM_WINDOWS
523 if (_stat(path, &s) != 0)
524 #elif defined PLATFORM_POSIX
526 if (stat(path, &s) != 0)
535 time_t CPlugin::GetTimeStamp()
540 void CPlugin::SetTimeStamp(time_t t)
545 void CPlugin::AddLangFile(unsigned int index)
547 m_PhraseFiles.push_back(index);
550 size_t CPlugin::GetLangFileCount()
552 return m_PhraseFiles.size();
555 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
557 return m_PhraseFiles.at(index);
560 void CPlugin::DependencyDropped(CPlugin *pOwner)
567 List<FakeNative *>::iterator iter;
571 unsigned int unbound = 0;
573 for (iter = pOwner->m_fakeNatives.begin();
574 iter != pOwner->m_fakeNatives.end();
578 /* Find this native! */
579 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
584 m_ctx.base->GetNativeByIndex(idx, &native);
586 native->status = SP_NATIVE_UNBOUND;
590 /* :IDEA: in the future, add native trapping? */
593 m_FakeNativesMissing = true;
594 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
597 m_dependsOn.remove(pOwner);
604 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
610 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
615 bool CPluginManager::CPluginIterator::MorePlugins()
617 return (current != mylist->end());
620 void CPluginManager::CPluginIterator::NextPlugin()
625 void CPluginManager::CPluginIterator::Release()
627 g_PluginSys.ReleaseIterator(this);
630 CPluginManager::CPluginIterator::~CPluginIterator()
634 void CPluginManager::CPluginIterator::Reset()
636 current = mylist->begin();
643 CPluginManager::CPluginManager()
645 m_LoadLookup = sm_trie_create();
646 m_AllPluginsLoaded = false;
648 m_pNativeLookup = sm_trie_create();
651 CPluginManager::~CPluginManager()
654 * Ignore the fact that there might be plugins in the cache.
655 * This usually means that Core is not being unloaded properly, and everything
656 * will crash anyway. YAY
658 sm_trie_destroy(m_LoadLookup);
659 sm_trie_destroy(m_pNativeLookup);
661 CStack<CPluginManager::CPluginIterator *>::iterator iter;
662 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
669 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
671 /* First read in the database of plugin settings */
673 unsigned int line, col;
674 m_AllPluginsLoaded = false;
675 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
677 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
678 const char *err_msg = g_TextParser.GetSMCErrorString(err);
681 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
685 LoadPluginsFromDir(basedir, NULL);
688 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
690 char base_path[PLATFORM_MAX_PATH];
692 /* Form the current path to start reading from */
693 if (localpath == NULL)
695 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
697 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
700 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
705 g_LibSys.GetPlatformError(error, sizeof(error));
706 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
707 g_Logger.LogError("[SM] Platform returned error: %s", error);
711 while (dir->MoreFiles())
713 if (dir->IsEntryDirectory()
714 && (strcmp(dir->GetEntryName(), ".") != 0)
715 && (strcmp(dir->GetEntryName(), "..") != 0)
716 && (strcmp(dir->GetEntryName(), "disabled") != 0)
717 && (strcmp(dir->GetEntryName(), "optional") != 0))
719 char new_local[PLATFORM_MAX_PATH];
720 if (localpath == NULL)
722 /* If no path yet, don't add a former slash */
723 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
725 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
727 LoadPluginsFromDir(basedir, new_local);
728 } else if (dir->IsEntryFile()) {
729 const char *name = dir->GetEntryName();
730 size_t len = strlen(name);
732 && strcmp(&name[len-4], ".smx") == 0)
734 /* If the filename matches, load the plugin */
735 char plugin[PLATFORM_MAX_PATH];
736 if (localpath == NULL)
738 snprintf(plugin, sizeof(plugin), "%s", name);
740 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
742 LoadAutoPlugin(plugin);
747 g_LibSys.CloseDirectory(dir);
750 //well i have discovered that gabe newell is very fat, so i wrote this comment now
751 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t err_max)
754 * Does this plugin already exist?
757 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
759 /* Check to see if we should try reloading it */
760 if (pPlugin->GetStatus() == Plugin_BadLoad
761 || pPlugin->GetStatus() == Plugin_Error
762 || pPlugin->GetStatus() == Plugin_Failed)
764 UnloadPlugin(pPlugin);
770 return LoadRes_AlreadyLoaded;
774 pPlugin = CPlugin::CreatePlugin(path, error, err_max);
776 assert(pPlugin != NULL);
778 pPlugin->m_type = PluginType_MapUpdated;
780 ICompilation *co = NULL;
782 if (pPlugin->m_status == Plugin_Uncompiled)
784 co = pPlugin->StartMyCompile(g_pVM);
787 PluginSettings *pset;
788 unsigned int setcount = m_PluginInfo.GetSettingsNum();
789 for (unsigned int i=0; i<setcount; i++)
791 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
795 pPlugin->m_type = pset->type_val;
798 for (unsigned int j=0; j<pset->opts_num; j++)
800 const char *key, *val;
801 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
806 if (!g_pVM->SetCompilationOption(co, key, val))
810 snprintf(error, err_max, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
812 pPlugin->CancelMyCompile();
820 /* Do the actual compiling */
823 pPlugin->FinishMyCompile(NULL, 0);
828 if (pPlugin->GetStatus() == Plugin_Created)
830 AddCoreNativesToPlugin(pPlugin);
831 pPlugin->InitIdentity();
832 if (pPlugin->Call_AskPluginLoad(error, err_max))
834 /* Autoload any modules */
835 LoadOrRequireExtensions(pPlugin, 1, error, err_max);
839 /* Save the time stamp */
840 time_t t = pPlugin->GetFileTimeStamp();
841 pPlugin->SetTimeStamp(t);
848 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
851 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t err_max, bool *wasloaded)
857 if ((res=_LoadPlugin(&pl, path, debug, type, error, err_max)) == LoadRes_Failure)
863 if (res == LoadRes_AlreadyLoaded)
871 /* Run second pass if we need to */
872 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
874 if (!RunSecondPass(pl, error, err_max))
884 void CPluginManager::LoadAutoPlugin(const char *plugin)
888 char error[255] = "Unknown error";
890 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
892 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
893 pl->SetErrorState(Plugin_Failed, "%s", error);
896 if (res == LoadRes_Successful)
902 void CPluginManager::AddPlugin(CPlugin *pPlugin)
904 List<IPluginsListener *>::iterator iter;
905 IPluginsListener *pListener;
907 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
910 pListener->OnPluginCreated(pPlugin);
913 m_plugins.push_back(pPlugin);
914 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
917 void CPluginManager::LoadAll_SecondPass()
919 List<CPlugin *>::iterator iter;
923 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
926 if (pPlugin->GetStatus() == Plugin_Loaded)
929 if (!RunSecondPass(pPlugin, error, sizeof(error)))
931 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
932 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
937 m_AllPluginsLoaded = true;
940 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
942 /* Find any extensions this plugin needs */
951 IPluginContext *pBase = pPlugin->GetBaseContext();
952 uint32_t num = pBase->GetPubVarsNum();
955 char path[PLATFORM_MAX_PATH];
957 for (uint32_t i=0; i<num; i++)
959 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
963 if (strncmp(pubvar->name, "__ext_", 6) == 0)
965 ext = (_ext *)pubvar->offs;
966 if (!ext->required && !ext->autoload)
970 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
974 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
980 /* Attempt to auto-load if necessary */
983 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
984 g_Extensions.LoadAutoExtension(path);
986 } else if (pass == 2) {
987 /* Is this required? */
990 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
991 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
993 pExt = g_Extensions.FindExtensionByName(name);
995 /* :TODO: should we bind to unloaded extensions?
996 * Currently the extension manager will ignore this.
998 if (!pExt || !pExt->IsRunning(NULL, 0))
1002 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1006 g_Extensions.BindChildPlugin(pExt, pPlugin);
1016 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1018 /* Second pass for extension requirements */
1019 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1024 /* Bind all extra natives */
1025 g_Extensions.BindAllNativesToPlugin(pPlugin);
1026 AddFakeNativesToPlugin(pPlugin);
1028 /* Find any unbound natives
1029 * Right now, these are not allowed
1031 IPluginContext *pContext = pPlugin->GetBaseContext();
1032 uint32_t num = pContext->GetNativesNum();
1033 sp_native_t *native;
1034 for (unsigned int i=0; i<num; i++)
1036 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1040 if (native->status == SP_NATIVE_UNBOUND)
1044 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1050 /* Finish by telling all listeners */
1051 List<IPluginsListener *>::iterator iter;
1052 IPluginsListener *pListener;
1053 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1055 pListener = (*iter);
1056 pListener->OnPluginLoaded(pPlugin);
1059 /* Tell this plugin to finish initializing itself */
1060 pPlugin->Call_OnPluginStart();
1062 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1063 if (pPlugin->m_fakeNatives.size())
1065 List<CPlugin *>::iterator pl_iter;
1067 for (pl_iter = m_plugins.begin();
1068 pl_iter != m_plugins.end();
1071 pOther = (*pl_iter);
1072 if (pOther->GetStatus() == Plugin_Error
1073 && pOther->m_FakeNativesMissing)
1075 TryRefreshNatives(pOther);
1083 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1085 List<sp_nativeinfo_t *>::iterator iter;
1087 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1089 sp_nativeinfo_t *natives = (*iter);
1090 IPluginContext *ctx = pPlugin->GetBaseContext();
1092 /* Attempt to bind every native! */
1093 while (natives[i].func != NULL)
1095 ctx->BindNative(&natives[i++]);
1100 void CPluginManager::TryRefreshNatives(CPlugin *pPlugin)
1102 assert(pPlugin->GetBaseContext() != NULL);
1104 AddFakeNativesToPlugin(pPlugin);
1106 /* Find any unbound natives
1107 * Right now, these are not allowed
1109 IPluginContext *pContext = pPlugin->GetBaseContext();
1110 uint32_t num = pContext->GetNativesNum();
1111 sp_native_t *native;
1112 for (unsigned int i=0; i<num; i++)
1114 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1118 if (native->status == SP_NATIVE_UNBOUND)
1120 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1125 /* If we got here, all natives are okay again! */
1126 pPlugin->m_status = Plugin_Running;
1127 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1129 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1130 _SetPauseState(pPlugin, false);
1134 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1136 IPluginContext *pContext = pPlugin->GetBaseContext();
1137 sp_nativeinfo_t native;
1139 List<FakeNative *>::iterator iter;
1140 FakeNative *pNative;
1142 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1145 ctx = pNative->ctx->GetContext();
1146 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1148 /* Ignore natives in paused plugins */
1151 native.name = pNative->name.c_str();
1152 native.func = pNative->func;
1153 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1155 /* Add us as a dependency, but we're careful not to do this circularly! */
1156 if (pNative->ctx != pContext)
1158 CPlugin *pOther = GetPluginByCtx(ctx);
1159 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1161 pOther->m_dependents.push_back(pPlugin);
1163 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1165 pPlugin->m_dependsOn.push_back(pOther);
1172 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1174 CPlugin *pPlugin = (CPlugin *)plugin;
1176 /* This prevents removal during insertion or anything else weird */
1177 if (m_plugins.find(pPlugin) == m_plugins.end())
1182 /* Remove us from the lookup table and linked list */
1183 m_plugins.remove(pPlugin);
1184 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1186 /* Go through all dependent plugins and tell them this plugin is now gone */
1187 List<CPlugin *>::iterator pl_iter;
1189 for (pl_iter = pPlugin->m_dependents.begin();
1190 pl_iter != pPlugin->m_dependents.end();
1193 pOther = (*pl_iter);
1194 pOther->DependencyDropped(pPlugin);
1197 /* Tell everyone we depend on that we no longer exist */
1198 for (pl_iter = pPlugin->m_dependsOn.begin();
1199 pl_iter != pPlugin->m_dependsOn.end();
1202 pOther = (*pl_iter);
1203 pOther->m_dependents.remove(pPlugin);
1206 /* Remove all of our native functions */
1207 List<FakeNative *>::iterator fn_iter;
1208 FakeNative *pNative;
1209 for (fn_iter = pPlugin->m_fakeNatives.begin();
1210 fn_iter != pPlugin->m_fakeNatives.end();
1213 pNative = (*fn_iter);
1214 m_Natives.remove(pNative);
1215 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1216 g_pVM->DestroyFakeNative(pNative->func);
1220 List<IPluginsListener *>::iterator iter;
1221 IPluginsListener *pListener;
1223 if (pPlugin->GetStatus() <= Plugin_Error)
1225 /* Notify listeners of unloading */
1226 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1228 pListener = (*iter);
1229 pListener->OnPluginUnloaded(pPlugin);
1232 pPlugin->Call_OnPluginEnd();
1235 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1237 /* Notify listeners of destruction */
1238 pListener = (*iter);
1239 pListener->OnPluginDestroyed(pPlugin);
1242 /* Tell the plugin to delete itself */
1248 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1250 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1254 unsigned int CPluginManager::GetPluginCount()
1256 return m_plugins.size();
1259 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1261 m_listeners.push_back(listener);
1264 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1266 m_listeners.remove(listener);
1269 IPluginIterator *CPluginManager::GetPluginIterator()
1271 if (m_iters.empty())
1273 return new CPluginIterator(&m_plugins);
1275 CPluginIterator *iter = m_iters.front();
1282 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1287 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1289 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1290 size_t alias_len = 0;
1291 size_t local_len = 0;
1293 const char *ptr = alias;
1294 unsigned int alias_explicit_paths = 0;
1295 unsigned int alias_path_end = 0;
1296 while (*ptr != '\0')
1298 if (*ptr == '\\' || *ptr == '/')
1300 alias_explicit_paths++;
1301 alias_path_end = alias_len;
1307 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1309 /* Trailing slash is totally invalid here */
1314 unsigned int local_explicit_paths = 0;
1315 unsigned int local_path_end = 0;
1316 while (*ptr != '\0')
1318 if (*ptr == '\\' || *ptr == '/')
1320 local_explicit_paths++;
1321 local_path_end = local_len;
1327 /* If the alias has more explicit paths than the real path,
1328 * no match will be possible.
1330 if (alias_explicit_paths > local_explicit_paths)
1335 if (alias_explicit_paths)
1337 /* We need to find if the paths match now. For example, these should all match:
1339 * csdm optional/csdm
1340 * csdm/ban optional/crab/csdm/ban
1342 const char *aliasptr = alias;
1343 const char *localptr = localpath;
1347 if (*aliasptr != *localptr)
1349 /* We have to knock one path off */
1350 local_explicit_paths--;
1351 if (alias_explicit_paths > local_explicit_paths)
1353 /* Skip out if we're gonna have an impossible match */
1356 /* Eat up localptr tokens until we get a result */
1357 while (((localptr - localpath) < (int)local_path_end)
1359 && *localptr != '\\')
1363 /* Check if we hit the end of our searchable area.
1364 * This probably isn't possible because of the path
1365 * count check, but it's a good idea anyway.
1367 if ((localptr - localpath) >= (int)local_path_end)
1371 /* Consume the slash token */
1374 /* Reset the alias pointer so we can continue consuming */
1380 * This is safe because if localptr terminates early, aliasptr will too
1384 /* We should never reach the end of the string because of this check. */
1385 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1386 bool localend = (localptr - localpath) > (int)local_path_end;
1387 if (aliasend || localend)
1389 if (aliasend && localend)
1391 /* we matched, and we can break out now */
1395 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1400 /* If we got here, it's safe to compare the next two tokens */
1401 if (*localptr != *aliasptr)
1412 /* If we got here, it's time to compare filenames */
1413 const char *aliasptr = alias;
1414 const char *localptr = localpath;
1416 if (alias_explicit_paths)
1418 aliasptr = &alias[alias_path_end + 1];
1421 if (local_explicit_paths)
1423 localptr = &localpath[local_path_end + 1];
1428 if (*aliasptr == '*')
1430 /* First, see if this is the last character */
1431 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1433 /* If so, there's no need to match anything else */
1436 /* Otherwise, we need to search for an appropriate matching sequence in local.
1437 * Note that we only need to search up to the next asterisk.
1441 const char *local_orig = localptr;
1445 while (*aliasptr != '\0' && *aliasptr != '*')
1447 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1448 if (*aliasptr != *localptr)
1458 /* If we didn't get a match, we need to advance the search stream.
1459 * This will let us skip tokens while still searching for another match.
1461 localptr = ++local_orig;
1462 /* Make sure we don't go out of bounds */
1463 if (*localptr == '\0')
1474 /* If we got a match, move on to the next token */
1477 } else if (*aliasptr == '\0') {
1478 if (*localptr == '\0'
1480 strcmp(localptr, ".smx") == 0)
1486 } else if (*aliasptr != *localptr) {
1496 bool CPluginManager::IsLateLoadTime() const
1498 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1501 void CPluginManager::OnSourceModAllInitialized()
1503 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1506 g_HandleSys.InitAccessDefaults(NULL, &sec);
1508 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1509 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1511 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1512 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1514 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1516 g_ShareSys.AddInterface(NULL, this);
1519 void CPluginManager::OnSourceModShutdown()
1521 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1523 List<CPlugin *>::iterator iter;
1524 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1526 UnloadPlugin((*iter));
1529 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1530 g_ShareSys.DestroyIdentType(g_PluginIdent);
1531 g_ShareSys.DestroyIdentity(m_MyIdent);
1534 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1536 /* We don't care about the internal object, actually */
1539 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1541 m_natives.push_back(natives);
1544 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1552 sec.pIdentity = m_MyIdent;
1554 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1567 CPlugin *CPluginManager::GetPluginByOrder(int num)
1569 if (num < 1 || num > (int)GetPluginCount())
1577 IPluginIterator *iter = GetPluginIterator();
1578 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1580 pl = (CPlugin *)(iter->GetPlugin());
1586 const char *CPluginManager::GetStatusText(PluginStatus st)
1590 case Plugin_Running:
1596 case Plugin_Uncompiled:
1597 return "Uncompiled";
1598 case Plugin_BadLoad:
1608 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1612 const char *cmd = g_RootMenu.GetArgument(2);
1613 if (strcmp(cmd, "list") == 0)
1616 unsigned int id = 1;
1617 int plnum = GetPluginCount();
1621 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1624 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1627 IPluginIterator *iter = GetPluginIterator();
1628 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1630 IPlugin *pl = iter->GetPlugin();
1631 assert(pl->GetStatus() != Plugin_Created);
1633 const sm_plugininfo_t *info = pl->GetPublicInfo();
1634 if (pl->GetStatus() != Plugin_Running)
1636 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1638 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1640 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1641 if (IS_STR_FILLED(info->version))
1643 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1645 if (IS_STR_FILLED(info->author))
1647 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1649 g_RootMenu.ConsolePrint("%s", buffer);
1654 } else if (strcmp(cmd, "load") == 0) {
1657 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1663 const char *filename = g_RootMenu.GetArgument(3);
1664 IPlugin *pl = LoadPlugin(filename, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1668 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", filename);
1674 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", filename);
1676 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", filename, error);
1680 } else if (strcmp(cmd, "unload") == 0) {
1683 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1688 int num = atoi(g_RootMenu.GetArgument(3));
1689 if (num < 1 || num > (int)GetPluginCount())
1691 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1695 IPluginIterator *iter = GetPluginIterator();
1696 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1698 IPlugin *pl = iter->GetPlugin();
1700 char name[PLATFORM_MAX_PATH];
1701 const sm_plugininfo_t *info = pl->GetPublicInfo();
1702 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1704 if (UnloadPlugin(pl))
1706 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1708 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1713 } else if (strcmp(cmd, "info") == 0) {
1716 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1720 int num = atoi(g_RootMenu.GetArgument(3));
1721 if (num < 1 || num > (int)GetPluginCount())
1723 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1727 CPlugin *pl = GetPluginByOrder(num);
1728 const sm_plugininfo_t *info = pl->GetPublicInfo();
1730 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1731 if (pl->GetStatus() <= Plugin_Error)
1733 if (IS_STR_FILLED(info->name))
1735 if (IS_STR_FILLED(info->description))
1737 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1739 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1742 if (IS_STR_FILLED(info->author))
1744 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1746 if (IS_STR_FILLED(info->version))
1748 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1750 if (IS_STR_FILLED(info->url))
1752 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1754 if (pl->GetStatus() == Plugin_Error)
1756 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
1758 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "yes" : "no");
1759 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "yes" : "no");
1762 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
1763 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
1764 info->name ? info->name : "<none>",
1765 info->version ? info->version : "<none>");
1766 if (IS_STR_FILLED(info->url))
1768 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
1773 } else if (strcmp(cmd, "debug") == 0) {
1776 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
1780 int num = atoi(g_RootMenu.GetArgument(3));
1781 if (num < 1 || num > (int)GetPluginCount())
1783 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1788 const char *mode = g_RootMenu.GetArgument(4);
1789 if ((res=strcmp("on", mode)) && strcmp("off", mode))
1791 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
1803 CPlugin *pl = GetPluginByOrder(num);
1804 if (debug && pl->IsDebugging())
1806 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
1808 } else if (!debug && !pl->IsDebugging()) {
1809 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
1814 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
1816 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
1819 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
1820 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
1826 /* Draw the main menu */
1827 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
1828 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
1829 g_RootMenu.DrawGenericOption("load", "Load a plugin");
1830 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
1831 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
1832 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
1835 void CPluginManager::ReloadOrUnloadPlugins()
1837 List<CPlugin *>::iterator iter;
1838 List<CPlugin *> tmp_list = m_plugins;
1842 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
1845 if (pl->GetType() == PluginType_MapOnly)
1847 UnloadPlugin((IPlugin *)pl);
1848 } else if (pl->GetType() == PluginType_MapUpdated) {
1849 t = pl->GetFileTimeStamp();
1850 if (!t || t > pl->GetTimeStamp())
1852 pl->SetTimeStamp(t);
1853 UnloadPlugin((IPlugin *)pl);
1859 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
1861 List<IPluginsListener *>::iterator iter;
1862 IPluginsListener *pListener;
1863 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1865 pListener = (*iter);
1866 pListener->OnPluginPauseChange(pl, paused);
1870 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
1872 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
1877 FakeNative *pNative = new FakeNative;
1879 pNative->func = g_pVM->CreateFakeNative(func, pNative);
1886 pNative->call = pFunction;
1887 pNative->name.assign(name);
1888 pNative->ctx = pFunction->GetParentContext();
1890 m_Natives.push_back(pNative);
1891 sm_trie_insert(m_pNativeLookup, name,pNative);
1893 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
1894 pPlugin->m_fakeNatives.push_back(pNative);
1899 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
1901 List<CPlugin *>::iterator iter;
1903 IPluginFunction *pFunction;
1905 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
1909 if (pPlugin->GetStatus() <= Plugin_Paused)
1911 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
1915 pForward->AddFunction(pFunction);