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"
30 #include "CoreConfig.h"
32 CPluginManager g_PluginSys;
33 HandleType_t g_PluginType = 0;
34 IdentityType_t g_PluginIdent = 0;
36 CPlugin::CPlugin(const char *file)
38 static int MySerial = 0;
40 m_type = PluginType_Private;
41 m_status = Plugin_Uncompiled;
42 m_serial = ++MySerial;
44 m_errormsg[256] = '\0';
45 snprintf(m_filename, sizeof(m_filename), "%s", file);
48 m_pProps = sm_trie_create();
49 m_FakeNativesMissing = false;
57 sec.pOwner = g_PluginSys.GetIdentity();
58 sec.pIdentity = sec.pOwner;
60 g_HandleSys.FreeHandle(m_handle, &sec);
61 g_ShareSys.DestroyIdentity(m_ident);
71 m_ctx.vm->FreeContext(m_ctx.ctx);
76 m_ctx.vm->AbortCompilation(m_ctx.co);
82 g_pSourcePawn->FreeFromMemory(m_plugin);
87 sm_trie_destroy(m_pProps);
89 for (size_t i=0; i<m_configs.size(); i++)
96 void CPlugin::InitIdentity()
100 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
101 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
102 m_ctx.base->SetIdentity(m_ident);
106 Handle_t CPlugin::GetMyHandle()
111 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
113 char fullpath[PLATFORM_MAX_PATH];
114 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
115 FILE *fp = fopen(fullpath, "rb");
117 CPlugin *pPlugin = new CPlugin(file);
123 snprintf(error, maxlength, "Unable to open file");
125 pPlugin->m_status = Plugin_BadLoad;
130 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
136 snprintf(error, maxlength, "Error %d while parsing plugin", err);
138 pPlugin->m_status = Plugin_BadLoad;
144 pPlugin->m_plugin = pl;
149 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
151 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
153 if (exists && remove)
155 sm_trie_delete(m_pProps, prop);
161 bool CPlugin::SetProperty(const char *prop, void *ptr)
163 return sm_trie_insert(m_pProps, prop, ptr);
166 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
173 /* :NOTICE: We will eventually need to change these natives
174 * for swapping in new contexts
176 if (m_ctx.co || m_ctx.ctx)
181 m_status = Plugin_Uncompiled;
184 m_ctx.co = vm->StartCompilation(m_plugin);
189 void CPlugin::CancelMyCompile()
196 m_ctx.vm->AbortCompilation(m_ctx.co);
201 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
209 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
212 memset(&m_ctx, 0, sizeof(m_ctx));
215 snprintf(error, maxlength, "JIT failed to compile (error %d)", err);
220 m_ctx.base = new BaseContext(m_ctx.ctx);
221 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
223 m_status = Plugin_Created;
231 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
233 PluginStatus old_status = m_status;
236 if (old_status == Plugin_Running)
238 /* Tell everyone we're now paused */
239 g_PluginSys._SetPauseState(this, true);
243 va_start(ap, error_fmt);
244 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
249 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
253 void CPlugin::UpdateInfo()
255 /* Now grab the info */
257 IPluginContext *base = GetBaseContext();
258 int err = base->FindPubvarByName("myinfo", &idx);
260 memset(&m_info, 0, sizeof(m_info));
262 if (err == SP_ERROR_NONE)
264 struct sm_plugininfo_c_t
272 sm_plugininfo_c_t *cinfo;
275 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
276 base->LocalToString(cinfo->name, (char **)&m_info.name);
277 base->LocalToString(cinfo->description, (char **)&m_info.description);
278 base->LocalToString(cinfo->author, (char **)&m_info.author);
279 base->LocalToString(cinfo->url, (char **)&m_info.url);
280 base->LocalToString(cinfo->version, (char **)&m_info.version);
283 m_info.author = m_info.author ? m_info.author : "";
284 m_info.description = m_info.description ? m_info.description : "";
285 m_info.name = m_info.name ? m_info.name : "";
286 m_info.url = m_info.url ? m_info.url : "";
287 m_info.version = m_info.version ? m_info.version : "";
290 void CPlugin::Call_OnPluginStart()
292 if (m_status != Plugin_Loaded)
297 m_status = Plugin_Running;
300 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
307 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
309 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
313 if ((pFunction = m_ctx.base->GetFunctionByName("OnMapStart")) != NULL)
315 pFunction->Execute(NULL);
318 if (SM_AreConfigsExecuted())
320 SM_ExecuteForPlugin(GetBaseContext());
325 void CPlugin::Call_OnPluginEnd()
327 if (m_status > Plugin_Paused)
333 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
339 pFunction->Execute(&result);
342 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
344 if (m_status != Plugin_Created)
349 m_status = Plugin_Loaded;
353 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
360 pFunction->PushCell(m_handle);
361 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
362 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
363 pFunction->PushCell(maxlength);
364 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
369 if (!result || m_status != Plugin_Loaded)
377 const sp_plugin_t *CPlugin::GetPluginStructure()
382 IPluginContext *CPlugin::GetBaseContext()
387 sp_context_t *CPlugin::GetContext()
392 const char *CPlugin::GetFilename()
397 PluginType CPlugin::GetType()
402 const sm_plugininfo_t *CPlugin::GetPublicInfo()
407 unsigned int CPlugin::GetSerial()
412 PluginStatus CPlugin::GetStatus()
417 bool CPlugin::IsDebugging()
424 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
427 bool CPlugin::SetPauseState(bool paused)
429 if (paused && GetStatus() != Plugin_Paused)
432 } else if (!paused && GetStatus() != Plugin_Running) {
436 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
440 pFunction->PushCell(paused ? 1 : 0);
441 pFunction->Execute(&result);
446 m_status = Plugin_Paused;
447 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
449 m_status = Plugin_Running;
450 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
453 g_PluginSys._SetPauseState(this, paused);
458 IdentityToken_t *CPlugin::GetIdentity()
463 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
471 snprintf(error, maxlength, "Plugin is not runnable.");
476 if (debug && IsDebugging())
480 snprintf(error, maxlength, "Plugin is already in debug mode.");
483 } else if (!debug && !IsDebugging()) {
486 snprintf(error, maxlength, "Plugins is already in production mode.");
491 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
492 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
496 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
501 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
505 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
506 new_ctx->hp = m_ctx.ctx->hp;
507 new_ctx->sp = m_ctx.ctx->sp;
508 new_ctx->frm = m_ctx.ctx->frm;
509 new_ctx->dbreak = m_ctx.ctx->dbreak;
510 new_ctx->context = m_ctx.ctx->context;
511 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
513 uint32_t nativeCount = m_plugin->info.natives_num;
514 for (uint32_t i=0; i<nativeCount; i++)
516 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
517 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
520 g_pVM->FreeContext(m_ctx.ctx);
522 m_ctx.base->SetContext(new_ctx);
528 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
536 bool CPlugin::IsRunnable()
538 return (m_status <= Plugin_Paused) ? true : false;
541 time_t CPlugin::GetFileTimeStamp()
543 char path[PLATFORM_MAX_PATH];
544 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
545 #ifdef PLATFORM_WINDOWS
547 if (_stat(path, &s) != 0)
548 #elif defined PLATFORM_POSIX
550 if (stat(path, &s) != 0)
559 time_t CPlugin::GetTimeStamp()
564 void CPlugin::SetTimeStamp(time_t t)
569 void CPlugin::AddLangFile(unsigned int index)
571 m_PhraseFiles.push_back(index);
574 size_t CPlugin::GetLangFileCount()
576 return m_PhraseFiles.size();
579 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
581 return m_PhraseFiles.at(index);
584 void CPlugin::DependencyDropped(CPlugin *pOwner)
591 List<FakeNative *>::iterator iter;
595 unsigned int unbound = 0;
597 for (iter = pOwner->m_fakeNatives.begin();
598 iter != pOwner->m_fakeNatives.end();
602 /* Find this native! */
603 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
608 m_ctx.base->GetNativeByIndex(idx, &native);
610 native->status = SP_NATIVE_UNBOUND;
614 /* :IDEA: in the future, add native trapping? */
617 m_FakeNativesMissing = true;
618 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
621 m_dependsOn.remove(pOwner);
624 unsigned int CPlugin::GetConfigCount()
626 return (unsigned int)m_configs.size();
629 AutoConfig *CPlugin::GetConfig(unsigned int i)
631 if (i >= GetConfigCount())
639 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
641 AutoConfig *c = new AutoConfig;
645 c->create = autoCreate;
647 m_configs.push_back(c);
654 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
660 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
665 bool CPluginManager::CPluginIterator::MorePlugins()
667 return (current != mylist->end());
670 void CPluginManager::CPluginIterator::NextPlugin()
675 void CPluginManager::CPluginIterator::Release()
677 g_PluginSys.ReleaseIterator(this);
680 CPluginManager::CPluginIterator::~CPluginIterator()
684 void CPluginManager::CPluginIterator::Reset()
686 current = mylist->begin();
693 CPluginManager::CPluginManager()
695 m_LoadLookup = sm_trie_create();
696 m_AllPluginsLoaded = false;
698 m_pNativeLookup = sm_trie_create();
701 CPluginManager::~CPluginManager()
704 * Ignore the fact that there might be plugins in the cache.
705 * This usually means that Core is not being unloaded properly, and everything
706 * will crash anyway. YAY
708 sm_trie_destroy(m_LoadLookup);
709 sm_trie_destroy(m_pNativeLookup);
711 CStack<CPluginManager::CPluginIterator *>::iterator iter;
712 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
719 void CPluginManager::Shutdown()
721 List<CPlugin *>::iterator iter;
723 while ((iter = m_plugins.begin()) != m_plugins.end())
729 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
731 /* First read in the database of plugin settings */
733 unsigned int line, col;
734 m_AllPluginsLoaded = false;
735 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
737 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
738 const char *err_msg = g_TextParser.GetSMCErrorString(err);
741 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
745 LoadPluginsFromDir(basedir, NULL);
748 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
750 char base_path[PLATFORM_MAX_PATH];
752 /* Form the current path to start reading from */
753 if (localpath == NULL)
755 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
757 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
760 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
765 g_LibSys.GetPlatformError(error, sizeof(error));
766 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
767 g_Logger.LogError("[SM] Platform returned error: %s", error);
771 while (dir->MoreFiles())
773 if (dir->IsEntryDirectory()
774 && (strcmp(dir->GetEntryName(), ".") != 0)
775 && (strcmp(dir->GetEntryName(), "..") != 0)
776 && (strcmp(dir->GetEntryName(), "disabled") != 0)
777 && (strcmp(dir->GetEntryName(), "optional") != 0))
779 char new_local[PLATFORM_MAX_PATH];
780 if (localpath == NULL)
782 /* If no path yet, don't add a former slash */
783 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
785 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
787 LoadPluginsFromDir(basedir, new_local);
788 } else if (dir->IsEntryFile()) {
789 const char *name = dir->GetEntryName();
790 size_t len = strlen(name);
792 && strcmp(&name[len-4], ".smx") == 0)
794 /* If the filename matches, load the plugin */
795 char plugin[PLATFORM_MAX_PATH];
796 if (localpath == NULL)
798 snprintf(plugin, sizeof(plugin), "%s", name);
800 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
802 LoadAutoPlugin(plugin);
807 g_LibSys.CloseDirectory(dir);
810 //well i have discovered that gabe newell is very fat, so i wrote this comment now
811 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
814 * Does this plugin already exist?
817 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
819 /* Check to see if we should try reloading it */
820 if (pPlugin->GetStatus() == Plugin_BadLoad
821 || pPlugin->GetStatus() == Plugin_Error
822 || pPlugin->GetStatus() == Plugin_Failed)
824 UnloadPlugin(pPlugin);
830 return LoadRes_AlreadyLoaded;
834 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
836 assert(pPlugin != NULL);
838 pPlugin->m_type = PluginType_MapUpdated;
840 ICompilation *co = NULL;
842 if (pPlugin->m_status == Plugin_Uncompiled)
844 co = pPlugin->StartMyCompile(g_pVM);
847 PluginSettings *pset;
848 unsigned int setcount = m_PluginInfo.GetSettingsNum();
849 for (unsigned int i=0; i<setcount; i++)
851 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
855 pPlugin->m_type = pset->type_val;
858 for (unsigned int j=0; j<pset->opts_num; j++)
860 const char *key, *val;
861 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
866 if (!g_pVM->SetCompilationOption(co, key, val))
870 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
872 pPlugin->CancelMyCompile();
880 /* Do the actual compiling */
883 pPlugin->FinishMyCompile(error, maxlength);
888 if (pPlugin->GetStatus() == Plugin_Created)
890 AddCoreNativesToPlugin(pPlugin);
891 pPlugin->InitIdentity();
892 if (pPlugin->Call_AskPluginLoad(error, maxlength))
894 /* Autoload any modules */
895 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
899 /* Save the time stamp */
900 time_t t = pPlugin->GetFileTimeStamp();
901 pPlugin->SetTimeStamp(t);
908 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
911 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
917 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
923 if (res == LoadRes_AlreadyLoaded)
931 /* Run second pass if we need to */
932 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
934 if (!RunSecondPass(pl, error, maxlength))
944 void CPluginManager::LoadAutoPlugin(const char *plugin)
948 char error[255] = "Unknown error";
950 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
952 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
953 pl->SetErrorState(Plugin_Failed, "%s", error);
956 if (res == LoadRes_Successful)
962 void CPluginManager::AddPlugin(CPlugin *pPlugin)
964 List<IPluginsListener *>::iterator iter;
965 IPluginsListener *pListener;
967 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
970 pListener->OnPluginCreated(pPlugin);
973 m_plugins.push_back(pPlugin);
974 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
977 void CPluginManager::LoadAll_SecondPass()
979 List<CPlugin *>::iterator iter;
983 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
986 if (pPlugin->GetStatus() == Plugin_Loaded)
989 if (!RunSecondPass(pPlugin, error, sizeof(error)))
991 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
992 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
997 m_AllPluginsLoaded = true;
1000 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1002 /* Find any extensions this plugin needs */
1011 IPluginContext *pBase = pPlugin->GetBaseContext();
1012 uint32_t num = pBase->GetPubVarsNum();
1013 sp_pubvar_t *pubvar;
1015 char path[PLATFORM_MAX_PATH];
1017 for (uint32_t i=0; i<num; i++)
1019 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1023 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1025 ext = (_ext *)pubvar->offs;
1026 if (!ext->required && !ext->autoload)
1030 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1034 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1040 /* Attempt to auto-load if necessary */
1043 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1044 g_Extensions.LoadAutoExtension(path);
1046 } else if (pass == 2) {
1047 /* Is this required? */
1050 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1051 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1053 pExt = g_Extensions.FindExtensionByName(name);
1055 /* :TODO: should we bind to unloaded extensions?
1056 * Currently the extension manager will ignore this.
1058 if (!pExt || !pExt->IsRunning(NULL, 0))
1062 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1066 g_Extensions.BindChildPlugin(pExt, pPlugin);
1076 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1078 /* Second pass for extension requirements */
1079 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1084 /* Bind all extra natives */
1085 g_Extensions.BindAllNativesToPlugin(pPlugin);
1086 AddFakeNativesToPlugin(pPlugin);
1088 /* Find any unbound natives
1089 * Right now, these are not allowed
1091 IPluginContext *pContext = pPlugin->GetBaseContext();
1092 uint32_t num = pContext->GetNativesNum();
1093 sp_native_t *native;
1094 for (unsigned int i=0; i<num; i++)
1096 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1100 if (native->status == SP_NATIVE_UNBOUND
1101 && native->name[0] != '@')
1105 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1111 /* Finish by telling all listeners */
1112 List<IPluginsListener *>::iterator iter;
1113 IPluginsListener *pListener;
1114 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1116 pListener = (*iter);
1117 pListener->OnPluginLoaded(pPlugin);
1120 /* Tell this plugin to finish initializing itself */
1121 pPlugin->Call_OnPluginStart();
1123 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1124 if (pPlugin->GetStatus() >= Plugin_Paused && pPlugin->m_fakeNatives.size())
1126 List<CPlugin *>::iterator pl_iter;
1128 for (pl_iter = m_plugins.begin();
1129 pl_iter != m_plugins.end();
1132 pOther = (*pl_iter);
1133 if (pOther->GetStatus() == Plugin_Error
1134 && pOther->m_FakeNativesMissing)
1136 TryRefreshNatives(pOther);
1144 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1146 List<sp_nativeinfo_t *>::iterator iter;
1148 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1150 sp_nativeinfo_t *natives = (*iter);
1151 IPluginContext *ctx = pPlugin->GetBaseContext();
1153 /* Attempt to bind every native! */
1154 while (natives[i].func != NULL)
1156 ctx->BindNative(&natives[i++]);
1161 void CPluginManager::TryRefreshNatives(CPlugin *pPlugin)
1163 assert(pPlugin->GetBaseContext() != NULL);
1165 AddFakeNativesToPlugin(pPlugin);
1167 /* Find any unbound natives
1168 * Right now, these are not allowed
1170 IPluginContext *pContext = pPlugin->GetBaseContext();
1171 uint32_t num = pContext->GetNativesNum();
1172 sp_native_t *native;
1173 for (unsigned int i=0; i<num; i++)
1175 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1179 if (native->status == SP_NATIVE_UNBOUND)
1181 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1186 /* If we got here, all natives are okay again! */
1187 pPlugin->m_status = Plugin_Running;
1188 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1190 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1191 _SetPauseState(pPlugin, false);
1195 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1197 IPluginContext *pContext = pPlugin->GetBaseContext();
1198 sp_nativeinfo_t native;
1200 List<FakeNative *>::iterator iter;
1201 FakeNative *pNative;
1203 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1206 ctx = pNative->ctx->GetContext();
1207 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1209 /* Ignore natives in paused plugins */
1212 native.name = pNative->name.c_str();
1213 native.func = pNative->func;
1214 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1216 /* Add us as a dependency, but we're careful not to do this circularly! */
1217 if (pNative->ctx != pContext)
1219 CPlugin *pOther = GetPluginByCtx(ctx);
1220 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1222 pOther->m_dependents.push_back(pPlugin);
1224 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1226 pPlugin->m_dependsOn.push_back(pOther);
1233 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1235 CPlugin *pPlugin = (CPlugin *)plugin;
1237 /* This prevents removal during insertion or anything else weird */
1238 if (m_plugins.find(pPlugin) == m_plugins.end())
1243 /* Remove us from the lookup table and linked list */
1244 m_plugins.remove(pPlugin);
1245 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1247 /* Go through all dependent plugins and tell them this plugin is now gone */
1248 List<CPlugin *>::iterator pl_iter;
1250 for (pl_iter = pPlugin->m_dependents.begin();
1251 pl_iter != pPlugin->m_dependents.end();
1254 pOther = (*pl_iter);
1255 pOther->DependencyDropped(pPlugin);
1258 /* Tell everyone we depend on that we no longer exist */
1259 for (pl_iter = pPlugin->m_dependsOn.begin();
1260 pl_iter != pPlugin->m_dependsOn.end();
1263 pOther = (*pl_iter);
1264 pOther->m_dependents.remove(pPlugin);
1267 /* Remove all of our native functions */
1268 List<FakeNative *>::iterator fn_iter;
1269 FakeNative *pNative;
1270 for (fn_iter = pPlugin->m_fakeNatives.begin();
1271 fn_iter != pPlugin->m_fakeNatives.end();
1274 pNative = (*fn_iter);
1275 m_Natives.remove(pNative);
1276 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1277 g_pVM->DestroyFakeNative(pNative->func);
1281 List<IPluginsListener *>::iterator iter;
1282 IPluginsListener *pListener;
1284 if (pPlugin->GetStatus() <= Plugin_Error)
1286 /* Notify listeners of unloading */
1287 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1289 pListener = (*iter);
1290 pListener->OnPluginUnloaded(pPlugin);
1293 pPlugin->Call_OnPluginEnd();
1296 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1298 /* Notify listeners of destruction */
1299 pListener = (*iter);
1300 pListener->OnPluginDestroyed(pPlugin);
1303 /* Tell the plugin to delete itself */
1309 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1311 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1315 unsigned int CPluginManager::GetPluginCount()
1317 return m_plugins.size();
1320 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1322 m_listeners.push_back(listener);
1325 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1327 m_listeners.remove(listener);
1330 IPluginIterator *CPluginManager::GetPluginIterator()
1332 if (m_iters.empty())
1334 return new CPluginIterator(&m_plugins);
1336 CPluginIterator *iter = m_iters.front();
1343 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1348 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1350 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1351 size_t alias_len = 0;
1352 size_t local_len = 0;
1354 const char *ptr = alias;
1355 unsigned int alias_explicit_paths = 0;
1356 unsigned int alias_path_end = 0;
1357 while (*ptr != '\0')
1359 if (*ptr == '\\' || *ptr == '/')
1361 alias_explicit_paths++;
1362 alias_path_end = alias_len;
1368 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1370 /* Trailing slash is totally invalid here */
1375 unsigned int local_explicit_paths = 0;
1376 unsigned int local_path_end = 0;
1377 while (*ptr != '\0')
1379 if (*ptr == '\\' || *ptr == '/')
1381 local_explicit_paths++;
1382 local_path_end = local_len;
1388 /* If the alias has more explicit paths than the real path,
1389 * no match will be possible.
1391 if (alias_explicit_paths > local_explicit_paths)
1396 if (alias_explicit_paths)
1398 /* We need to find if the paths match now. For example, these should all match:
1400 * csdm optional/csdm
1401 * csdm/ban optional/crab/csdm/ban
1403 const char *aliasptr = alias;
1404 const char *localptr = localpath;
1408 if (*aliasptr != *localptr)
1410 /* We have to knock one path off */
1411 local_explicit_paths--;
1412 if (alias_explicit_paths > local_explicit_paths)
1414 /* Skip out if we're gonna have an impossible match */
1417 /* Eat up localptr tokens until we get a result */
1418 while (((localptr - localpath) < (int)local_path_end)
1420 && *localptr != '\\')
1424 /* Check if we hit the end of our searchable area.
1425 * This probably isn't possible because of the path
1426 * count check, but it's a good idea anyway.
1428 if ((localptr - localpath) >= (int)local_path_end)
1432 /* Consume the slash token */
1435 /* Reset the alias pointer so we can continue consuming */
1441 * This is safe because if localptr terminates early, aliasptr will too
1445 /* We should never reach the end of the string because of this check. */
1446 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1447 bool localend = (localptr - localpath) > (int)local_path_end;
1448 if (aliasend || localend)
1450 if (aliasend && localend)
1452 /* we matched, and we can break out now */
1456 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1461 /* If we got here, it's safe to compare the next two tokens */
1462 if (*localptr != *aliasptr)
1473 /* If we got here, it's time to compare filenames */
1474 const char *aliasptr = alias;
1475 const char *localptr = localpath;
1477 if (alias_explicit_paths)
1479 aliasptr = &alias[alias_path_end + 1];
1482 if (local_explicit_paths)
1484 localptr = &localpath[local_path_end + 1];
1489 if (*aliasptr == '*')
1491 /* First, see if this is the last character */
1492 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1494 /* If so, there's no need to match anything else */
1497 /* Otherwise, we need to search for an appropriate matching sequence in local.
1498 * Note that we only need to search up to the next asterisk.
1502 const char *local_orig = localptr;
1506 while (*aliasptr != '\0' && *aliasptr != '*')
1508 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1509 if (*aliasptr != *localptr)
1519 /* If we didn't get a match, we need to advance the search stream.
1520 * This will let us skip tokens while still searching for another match.
1522 localptr = ++local_orig;
1523 /* Make sure we don't go out of bounds */
1524 if (*localptr == '\0')
1535 /* If we got a match, move on to the next token */
1538 } else if (*aliasptr == '\0') {
1539 if (*localptr == '\0'
1541 strcmp(localptr, ".smx") == 0)
1547 } else if (*aliasptr != *localptr) {
1557 bool CPluginManager::IsLateLoadTime() const
1559 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1562 void CPluginManager::OnSourceModAllInitialized()
1564 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1567 g_HandleSys.InitAccessDefaults(NULL, &sec);
1569 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1570 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1572 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1573 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1575 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1577 g_ShareSys.AddInterface(NULL, this);
1580 void CPluginManager::OnSourceModShutdown()
1582 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1584 List<CPlugin *>::iterator iter;
1585 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1587 UnloadPlugin((*iter));
1590 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1591 g_ShareSys.DestroyIdentType(g_PluginIdent);
1592 g_ShareSys.DestroyIdentity(m_MyIdent);
1595 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1597 /* We don't care about the internal object, actually */
1600 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1602 m_natives.push_back(natives);
1605 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1613 sec.pIdentity = m_MyIdent;
1615 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1628 CPlugin *CPluginManager::GetPluginByOrder(int num)
1630 if (num < 1 || num > (int)GetPluginCount())
1638 IPluginIterator *iter = GetPluginIterator();
1639 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1641 pl = (CPlugin *)(iter->GetPlugin());
1647 const char *CPluginManager::GetStatusText(PluginStatus st)
1651 case Plugin_Running:
1657 case Plugin_Uncompiled:
1658 return "Uncompiled";
1659 case Plugin_BadLoad:
1669 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1673 const char *cmd = g_RootMenu.GetArgument(2);
1674 if (strcmp(cmd, "list") == 0)
1677 unsigned int id = 1;
1678 int plnum = GetPluginCount();
1682 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1685 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1688 IPluginIterator *iter = GetPluginIterator();
1689 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1691 IPlugin *pl = iter->GetPlugin();
1692 assert(pl->GetStatus() != Plugin_Created);
1694 const sm_plugininfo_t *info = pl->GetPublicInfo();
1695 if (pl->GetStatus() != Plugin_Running)
1697 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1699 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1701 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1702 if (IS_STR_FILLED(info->version))
1704 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1706 if (IS_STR_FILLED(info->author))
1708 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1710 g_RootMenu.ConsolePrint("%s", buffer);
1715 } else if (strcmp(cmd, "load") == 0) {
1718 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1724 const char *filename = g_RootMenu.GetArgument(3);
1726 char pluginfile[256];
1727 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1728 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1730 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1734 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1740 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1742 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
1746 } else if (strcmp(cmd, "unload") == 0) {
1749 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1754 int num = atoi(g_RootMenu.GetArgument(3));
1755 if (num < 1 || num > (int)GetPluginCount())
1757 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1761 IPluginIterator *iter = GetPluginIterator();
1762 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1764 IPlugin *pl = iter->GetPlugin();
1766 char name[PLATFORM_MAX_PATH];
1767 const sm_plugininfo_t *info = pl->GetPublicInfo();
1768 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1770 if (UnloadPlugin(pl))
1772 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1774 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1779 } else if (strcmp(cmd, "info") == 0) {
1782 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1786 int num = atoi(g_RootMenu.GetArgument(3));
1787 if (num < 1 || num > (int)GetPluginCount())
1789 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1793 CPlugin *pl = GetPluginByOrder(num);
1794 const sm_plugininfo_t *info = pl->GetPublicInfo();
1796 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1797 if (pl->GetStatus() <= Plugin_Error)
1799 if (IS_STR_FILLED(info->name))
1801 if (IS_STR_FILLED(info->description))
1803 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1805 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1808 if (IS_STR_FILLED(info->author))
1810 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1812 if (IS_STR_FILLED(info->version))
1814 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1816 if (IS_STR_FILLED(info->url))
1818 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1820 if (pl->GetStatus() == Plugin_Error)
1822 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
1824 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
1825 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
1827 const char *typestr = "";
1828 switch (pl->GetType())
1830 case PluginType_MapUpdated:
1831 typestr = "Map Change if Updated";
1833 case PluginType_MapOnly:
1834 typestr = "Map Change";
1836 case PluginType_Private:
1837 case PluginType_Global:
1842 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
1845 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
1846 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
1847 info->name ? info->name : "<none>",
1848 info->version ? info->version : "<none>");
1849 if (IS_STR_FILLED(info->url))
1851 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
1856 } else if (strcmp(cmd, "debug") == 0) {
1859 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
1863 int num = atoi(g_RootMenu.GetArgument(3));
1864 if (num < 1 || num > (int)GetPluginCount())
1866 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1871 const char *mode = g_RootMenu.GetArgument(4);
1872 if ((res=strcmp("on", mode)) && strcmp("off", mode))
1874 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
1886 CPlugin *pl = GetPluginByOrder(num);
1887 if (debug && pl->IsDebugging())
1889 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
1891 } else if (!debug && !pl->IsDebugging()) {
1892 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
1897 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
1899 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
1902 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
1903 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
1909 /* Draw the main menu */
1910 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
1911 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
1912 g_RootMenu.DrawGenericOption("load", "Load a plugin");
1913 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
1914 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
1915 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
1918 void CPluginManager::ReloadOrUnloadPlugins()
1920 List<CPlugin *>::iterator iter;
1921 List<CPlugin *> tmp_list = m_plugins;
1925 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
1928 if (pl->GetType() == PluginType_MapOnly)
1930 UnloadPlugin((IPlugin *)pl);
1931 } else if (pl->GetType() == PluginType_MapUpdated) {
1932 t = pl->GetFileTimeStamp();
1933 if (!t || t > pl->GetTimeStamp())
1935 pl->SetTimeStamp(t);
1936 UnloadPlugin((IPlugin *)pl);
1942 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
1944 List<IPluginsListener *>::iterator iter;
1945 IPluginsListener *pListener;
1946 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1948 pListener = (*iter);
1949 pListener->OnPluginPauseChange(pl, paused);
1953 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
1955 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
1960 FakeNative *pNative = new FakeNative;
1962 pNative->func = g_pVM->CreateFakeNative(func, pNative);
1969 pNative->call = pFunction;
1970 pNative->name.assign(name);
1971 pNative->ctx = pFunction->GetParentContext();
1973 m_Natives.push_back(pNative);
1974 sm_trie_insert(m_pNativeLookup, name,pNative);
1976 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
1977 pPlugin->m_fakeNatives.push_back(pNative);
1982 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
1984 List<CPlugin *>::iterator iter;
1986 IPluginFunction *pFunction;
1988 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
1992 if (pPlugin->GetStatus() <= Plugin_Paused)
1994 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
1998 pForward->AddFunction(pFunction);
2004 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2006 if (pToken->type != g_PluginIdent)
2011 return (CPlugin *)(pToken->ptr);
2014 void CPluginManager::ExecAndGenPluginConfs()
2016 List<CPlugin *>::iterator iter;