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::LoadAll_FirstPass(const char *config, const char *basedir)
721 /* First read in the database of plugin settings */
723 unsigned int line, col;
724 m_AllPluginsLoaded = false;
725 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
727 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
728 const char *err_msg = g_TextParser.GetSMCErrorString(err);
731 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
735 LoadPluginsFromDir(basedir, NULL);
738 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
740 char base_path[PLATFORM_MAX_PATH];
742 /* Form the current path to start reading from */
743 if (localpath == NULL)
745 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
747 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
750 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
755 g_LibSys.GetPlatformError(error, sizeof(error));
756 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
757 g_Logger.LogError("[SM] Platform returned error: %s", error);
761 while (dir->MoreFiles())
763 if (dir->IsEntryDirectory()
764 && (strcmp(dir->GetEntryName(), ".") != 0)
765 && (strcmp(dir->GetEntryName(), "..") != 0)
766 && (strcmp(dir->GetEntryName(), "disabled") != 0)
767 && (strcmp(dir->GetEntryName(), "optional") != 0))
769 char new_local[PLATFORM_MAX_PATH];
770 if (localpath == NULL)
772 /* If no path yet, don't add a former slash */
773 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
775 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
777 LoadPluginsFromDir(basedir, new_local);
778 } else if (dir->IsEntryFile()) {
779 const char *name = dir->GetEntryName();
780 size_t len = strlen(name);
782 && strcmp(&name[len-4], ".smx") == 0)
784 /* If the filename matches, load the plugin */
785 char plugin[PLATFORM_MAX_PATH];
786 if (localpath == NULL)
788 snprintf(plugin, sizeof(plugin), "%s", name);
790 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
792 LoadAutoPlugin(plugin);
797 g_LibSys.CloseDirectory(dir);
800 //well i have discovered that gabe newell is very fat, so i wrote this comment now
801 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
804 * Does this plugin already exist?
807 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
809 /* Check to see if we should try reloading it */
810 if (pPlugin->GetStatus() == Plugin_BadLoad
811 || pPlugin->GetStatus() == Plugin_Error
812 || pPlugin->GetStatus() == Plugin_Failed)
814 UnloadPlugin(pPlugin);
820 return LoadRes_AlreadyLoaded;
824 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
826 assert(pPlugin != NULL);
828 pPlugin->m_type = PluginType_MapUpdated;
830 ICompilation *co = NULL;
832 if (pPlugin->m_status == Plugin_Uncompiled)
834 co = pPlugin->StartMyCompile(g_pVM);
837 PluginSettings *pset;
838 unsigned int setcount = m_PluginInfo.GetSettingsNum();
839 for (unsigned int i=0; i<setcount; i++)
841 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
845 pPlugin->m_type = pset->type_val;
848 for (unsigned int j=0; j<pset->opts_num; j++)
850 const char *key, *val;
851 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
856 if (!g_pVM->SetCompilationOption(co, key, val))
860 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
862 pPlugin->CancelMyCompile();
870 /* Do the actual compiling */
873 pPlugin->FinishMyCompile(error, maxlength);
878 if (pPlugin->GetStatus() == Plugin_Created)
880 AddCoreNativesToPlugin(pPlugin);
881 pPlugin->InitIdentity();
882 if (pPlugin->Call_AskPluginLoad(error, maxlength))
884 /* Autoload any modules */
885 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
889 /* Save the time stamp */
890 time_t t = pPlugin->GetFileTimeStamp();
891 pPlugin->SetTimeStamp(t);
898 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
901 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
907 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
913 if (res == LoadRes_AlreadyLoaded)
921 /* Run second pass if we need to */
922 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
924 if (!RunSecondPass(pl, error, maxlength))
934 void CPluginManager::LoadAutoPlugin(const char *plugin)
938 char error[255] = "Unknown error";
940 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
942 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
943 pl->SetErrorState(Plugin_Failed, "%s", error);
946 if (res == LoadRes_Successful)
952 void CPluginManager::AddPlugin(CPlugin *pPlugin)
954 List<IPluginsListener *>::iterator iter;
955 IPluginsListener *pListener;
957 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
960 pListener->OnPluginCreated(pPlugin);
963 m_plugins.push_back(pPlugin);
964 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
967 void CPluginManager::LoadAll_SecondPass()
969 List<CPlugin *>::iterator iter;
973 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
976 if (pPlugin->GetStatus() == Plugin_Loaded)
979 if (!RunSecondPass(pPlugin, error, sizeof(error)))
981 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
982 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
987 m_AllPluginsLoaded = true;
990 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
992 /* Find any extensions this plugin needs */
1001 IPluginContext *pBase = pPlugin->GetBaseContext();
1002 uint32_t num = pBase->GetPubVarsNum();
1003 sp_pubvar_t *pubvar;
1005 char path[PLATFORM_MAX_PATH];
1007 for (uint32_t i=0; i<num; i++)
1009 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1013 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1015 ext = (_ext *)pubvar->offs;
1016 if (!ext->required && !ext->autoload)
1020 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1024 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1030 /* Attempt to auto-load if necessary */
1033 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1034 g_Extensions.LoadAutoExtension(path);
1036 } else if (pass == 2) {
1037 /* Is this required? */
1040 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1041 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1043 pExt = g_Extensions.FindExtensionByName(name);
1045 /* :TODO: should we bind to unloaded extensions?
1046 * Currently the extension manager will ignore this.
1048 if (!pExt || !pExt->IsRunning(NULL, 0))
1052 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1056 g_Extensions.BindChildPlugin(pExt, pPlugin);
1066 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1068 /* Second pass for extension requirements */
1069 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1074 /* Bind all extra natives */
1075 g_Extensions.BindAllNativesToPlugin(pPlugin);
1076 AddFakeNativesToPlugin(pPlugin);
1078 /* Find any unbound natives
1079 * Right now, these are not allowed
1081 IPluginContext *pContext = pPlugin->GetBaseContext();
1082 uint32_t num = pContext->GetNativesNum();
1083 sp_native_t *native;
1084 for (unsigned int i=0; i<num; i++)
1086 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1090 if (native->status == SP_NATIVE_UNBOUND
1091 && native->name[0] != '@')
1095 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1101 /* Finish by telling all listeners */
1102 List<IPluginsListener *>::iterator iter;
1103 IPluginsListener *pListener;
1104 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1106 pListener = (*iter);
1107 pListener->OnPluginLoaded(pPlugin);
1110 /* Tell this plugin to finish initializing itself */
1111 pPlugin->Call_OnPluginStart();
1113 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1114 if (pPlugin->GetStatus() >= Plugin_Paused && pPlugin->m_fakeNatives.size())
1116 List<CPlugin *>::iterator pl_iter;
1118 for (pl_iter = m_plugins.begin();
1119 pl_iter != m_plugins.end();
1122 pOther = (*pl_iter);
1123 if (pOther->GetStatus() == Plugin_Error
1124 && pOther->m_FakeNativesMissing)
1126 TryRefreshNatives(pOther);
1134 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1136 List<sp_nativeinfo_t *>::iterator iter;
1138 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1140 sp_nativeinfo_t *natives = (*iter);
1141 IPluginContext *ctx = pPlugin->GetBaseContext();
1143 /* Attempt to bind every native! */
1144 while (natives[i].func != NULL)
1146 ctx->BindNative(&natives[i++]);
1151 void CPluginManager::TryRefreshNatives(CPlugin *pPlugin)
1153 assert(pPlugin->GetBaseContext() != NULL);
1155 AddFakeNativesToPlugin(pPlugin);
1157 /* Find any unbound natives
1158 * Right now, these are not allowed
1160 IPluginContext *pContext = pPlugin->GetBaseContext();
1161 uint32_t num = pContext->GetNativesNum();
1162 sp_native_t *native;
1163 for (unsigned int i=0; i<num; i++)
1165 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1169 if (native->status == SP_NATIVE_UNBOUND)
1171 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1176 /* If we got here, all natives are okay again! */
1177 pPlugin->m_status = Plugin_Running;
1178 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1180 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1181 _SetPauseState(pPlugin, false);
1185 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1187 IPluginContext *pContext = pPlugin->GetBaseContext();
1188 sp_nativeinfo_t native;
1190 List<FakeNative *>::iterator iter;
1191 FakeNative *pNative;
1193 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1196 ctx = pNative->ctx->GetContext();
1197 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1199 /* Ignore natives in paused plugins */
1202 native.name = pNative->name.c_str();
1203 native.func = pNative->func;
1204 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1206 /* Add us as a dependency, but we're careful not to do this circularly! */
1207 if (pNative->ctx != pContext)
1209 CPlugin *pOther = GetPluginByCtx(ctx);
1210 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1212 pOther->m_dependents.push_back(pPlugin);
1214 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1216 pPlugin->m_dependsOn.push_back(pOther);
1223 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1225 CPlugin *pPlugin = (CPlugin *)plugin;
1227 /* This prevents removal during insertion or anything else weird */
1228 if (m_plugins.find(pPlugin) == m_plugins.end())
1233 /* Remove us from the lookup table and linked list */
1234 m_plugins.remove(pPlugin);
1235 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1237 /* Go through all dependent plugins and tell them this plugin is now gone */
1238 List<CPlugin *>::iterator pl_iter;
1240 for (pl_iter = pPlugin->m_dependents.begin();
1241 pl_iter != pPlugin->m_dependents.end();
1244 pOther = (*pl_iter);
1245 pOther->DependencyDropped(pPlugin);
1248 /* Tell everyone we depend on that we no longer exist */
1249 for (pl_iter = pPlugin->m_dependsOn.begin();
1250 pl_iter != pPlugin->m_dependsOn.end();
1253 pOther = (*pl_iter);
1254 pOther->m_dependents.remove(pPlugin);
1257 /* Remove all of our native functions */
1258 List<FakeNative *>::iterator fn_iter;
1259 FakeNative *pNative;
1260 for (fn_iter = pPlugin->m_fakeNatives.begin();
1261 fn_iter != pPlugin->m_fakeNatives.end();
1264 pNative = (*fn_iter);
1265 m_Natives.remove(pNative);
1266 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1267 g_pVM->DestroyFakeNative(pNative->func);
1271 List<IPluginsListener *>::iterator iter;
1272 IPluginsListener *pListener;
1274 if (pPlugin->GetStatus() <= Plugin_Error)
1276 /* Notify listeners of unloading */
1277 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1279 pListener = (*iter);
1280 pListener->OnPluginUnloaded(pPlugin);
1283 pPlugin->Call_OnPluginEnd();
1286 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1288 /* Notify listeners of destruction */
1289 pListener = (*iter);
1290 pListener->OnPluginDestroyed(pPlugin);
1293 /* Tell the plugin to delete itself */
1299 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1301 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1305 unsigned int CPluginManager::GetPluginCount()
1307 return m_plugins.size();
1310 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1312 m_listeners.push_back(listener);
1315 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1317 m_listeners.remove(listener);
1320 IPluginIterator *CPluginManager::GetPluginIterator()
1322 if (m_iters.empty())
1324 return new CPluginIterator(&m_plugins);
1326 CPluginIterator *iter = m_iters.front();
1333 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1338 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1340 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1341 size_t alias_len = 0;
1342 size_t local_len = 0;
1344 const char *ptr = alias;
1345 unsigned int alias_explicit_paths = 0;
1346 unsigned int alias_path_end = 0;
1347 while (*ptr != '\0')
1349 if (*ptr == '\\' || *ptr == '/')
1351 alias_explicit_paths++;
1352 alias_path_end = alias_len;
1358 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1360 /* Trailing slash is totally invalid here */
1365 unsigned int local_explicit_paths = 0;
1366 unsigned int local_path_end = 0;
1367 while (*ptr != '\0')
1369 if (*ptr == '\\' || *ptr == '/')
1371 local_explicit_paths++;
1372 local_path_end = local_len;
1378 /* If the alias has more explicit paths than the real path,
1379 * no match will be possible.
1381 if (alias_explicit_paths > local_explicit_paths)
1386 if (alias_explicit_paths)
1388 /* We need to find if the paths match now. For example, these should all match:
1390 * csdm optional/csdm
1391 * csdm/ban optional/crab/csdm/ban
1393 const char *aliasptr = alias;
1394 const char *localptr = localpath;
1398 if (*aliasptr != *localptr)
1400 /* We have to knock one path off */
1401 local_explicit_paths--;
1402 if (alias_explicit_paths > local_explicit_paths)
1404 /* Skip out if we're gonna have an impossible match */
1407 /* Eat up localptr tokens until we get a result */
1408 while (((localptr - localpath) < (int)local_path_end)
1410 && *localptr != '\\')
1414 /* Check if we hit the end of our searchable area.
1415 * This probably isn't possible because of the path
1416 * count check, but it's a good idea anyway.
1418 if ((localptr - localpath) >= (int)local_path_end)
1422 /* Consume the slash token */
1425 /* Reset the alias pointer so we can continue consuming */
1431 * This is safe because if localptr terminates early, aliasptr will too
1435 /* We should never reach the end of the string because of this check. */
1436 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1437 bool localend = (localptr - localpath) > (int)local_path_end;
1438 if (aliasend || localend)
1440 if (aliasend && localend)
1442 /* we matched, and we can break out now */
1446 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1451 /* If we got here, it's safe to compare the next two tokens */
1452 if (*localptr != *aliasptr)
1463 /* If we got here, it's time to compare filenames */
1464 const char *aliasptr = alias;
1465 const char *localptr = localpath;
1467 if (alias_explicit_paths)
1469 aliasptr = &alias[alias_path_end + 1];
1472 if (local_explicit_paths)
1474 localptr = &localpath[local_path_end + 1];
1479 if (*aliasptr == '*')
1481 /* First, see if this is the last character */
1482 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1484 /* If so, there's no need to match anything else */
1487 /* Otherwise, we need to search for an appropriate matching sequence in local.
1488 * Note that we only need to search up to the next asterisk.
1492 const char *local_orig = localptr;
1496 while (*aliasptr != '\0' && *aliasptr != '*')
1498 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1499 if (*aliasptr != *localptr)
1509 /* If we didn't get a match, we need to advance the search stream.
1510 * This will let us skip tokens while still searching for another match.
1512 localptr = ++local_orig;
1513 /* Make sure we don't go out of bounds */
1514 if (*localptr == '\0')
1525 /* If we got a match, move on to the next token */
1528 } else if (*aliasptr == '\0') {
1529 if (*localptr == '\0'
1531 strcmp(localptr, ".smx") == 0)
1537 } else if (*aliasptr != *localptr) {
1547 bool CPluginManager::IsLateLoadTime() const
1549 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1552 void CPluginManager::OnSourceModAllInitialized()
1554 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1557 g_HandleSys.InitAccessDefaults(NULL, &sec);
1559 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1560 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1562 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1563 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1565 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1567 g_ShareSys.AddInterface(NULL, this);
1570 void CPluginManager::OnSourceModShutdown()
1572 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1574 List<CPlugin *>::iterator iter;
1575 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1577 UnloadPlugin((*iter));
1580 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1581 g_ShareSys.DestroyIdentType(g_PluginIdent);
1582 g_ShareSys.DestroyIdentity(m_MyIdent);
1585 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1587 /* We don't care about the internal object, actually */
1590 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1592 m_natives.push_back(natives);
1595 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1603 sec.pIdentity = m_MyIdent;
1605 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1618 CPlugin *CPluginManager::GetPluginByOrder(int num)
1620 if (num < 1 || num > (int)GetPluginCount())
1628 IPluginIterator *iter = GetPluginIterator();
1629 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1631 pl = (CPlugin *)(iter->GetPlugin());
1637 const char *CPluginManager::GetStatusText(PluginStatus st)
1641 case Plugin_Running:
1647 case Plugin_Uncompiled:
1648 return "Uncompiled";
1649 case Plugin_BadLoad:
1659 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1663 const char *cmd = g_RootMenu.GetArgument(2);
1664 if (strcmp(cmd, "list") == 0)
1667 unsigned int id = 1;
1668 int plnum = GetPluginCount();
1672 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1675 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1678 IPluginIterator *iter = GetPluginIterator();
1679 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1681 IPlugin *pl = iter->GetPlugin();
1682 assert(pl->GetStatus() != Plugin_Created);
1684 const sm_plugininfo_t *info = pl->GetPublicInfo();
1685 if (pl->GetStatus() != Plugin_Running)
1687 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1689 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1691 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1692 if (IS_STR_FILLED(info->version))
1694 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1696 if (IS_STR_FILLED(info->author))
1698 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1700 g_RootMenu.ConsolePrint("%s", buffer);
1705 } else if (strcmp(cmd, "load") == 0) {
1708 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1714 const char *filename = g_RootMenu.GetArgument(3);
1716 char pluginfile[256];
1717 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1718 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1720 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1724 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1730 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1732 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
1736 } else if (strcmp(cmd, "unload") == 0) {
1739 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1744 int num = atoi(g_RootMenu.GetArgument(3));
1745 if (num < 1 || num > (int)GetPluginCount())
1747 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1751 IPluginIterator *iter = GetPluginIterator();
1752 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1754 IPlugin *pl = iter->GetPlugin();
1756 char name[PLATFORM_MAX_PATH];
1757 const sm_plugininfo_t *info = pl->GetPublicInfo();
1758 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1760 if (UnloadPlugin(pl))
1762 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1764 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1769 } else if (strcmp(cmd, "info") == 0) {
1772 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1776 int num = atoi(g_RootMenu.GetArgument(3));
1777 if (num < 1 || num > (int)GetPluginCount())
1779 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1783 CPlugin *pl = GetPluginByOrder(num);
1784 const sm_plugininfo_t *info = pl->GetPublicInfo();
1786 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1787 if (pl->GetStatus() <= Plugin_Error)
1789 if (IS_STR_FILLED(info->name))
1791 if (IS_STR_FILLED(info->description))
1793 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1795 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1798 if (IS_STR_FILLED(info->author))
1800 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1802 if (IS_STR_FILLED(info->version))
1804 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1806 if (IS_STR_FILLED(info->url))
1808 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1810 if (pl->GetStatus() == Plugin_Error)
1812 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
1814 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
1815 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
1817 const char *typestr = "";
1818 switch (pl->GetType())
1820 case PluginType_MapUpdated:
1821 typestr = "Map Change if Updated";
1823 case PluginType_MapOnly:
1824 typestr = "Map Change";
1826 case PluginType_Private:
1827 case PluginType_Global:
1832 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
1835 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
1836 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
1837 info->name ? info->name : "<none>",
1838 info->version ? info->version : "<none>");
1839 if (IS_STR_FILLED(info->url))
1841 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
1846 } else if (strcmp(cmd, "debug") == 0) {
1849 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
1853 int num = atoi(g_RootMenu.GetArgument(3));
1854 if (num < 1 || num > (int)GetPluginCount())
1856 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1861 const char *mode = g_RootMenu.GetArgument(4);
1862 if ((res=strcmp("on", mode)) && strcmp("off", mode))
1864 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
1876 CPlugin *pl = GetPluginByOrder(num);
1877 if (debug && pl->IsDebugging())
1879 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
1881 } else if (!debug && !pl->IsDebugging()) {
1882 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
1887 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
1889 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
1892 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
1893 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
1899 /* Draw the main menu */
1900 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
1901 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
1902 g_RootMenu.DrawGenericOption("load", "Load a plugin");
1903 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
1904 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
1905 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
1908 void CPluginManager::ReloadOrUnloadPlugins()
1910 List<CPlugin *>::iterator iter;
1911 List<CPlugin *> tmp_list = m_plugins;
1915 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
1918 if (pl->GetType() == PluginType_MapOnly)
1920 UnloadPlugin((IPlugin *)pl);
1921 } else if (pl->GetType() == PluginType_MapUpdated) {
1922 t = pl->GetFileTimeStamp();
1923 if (!t || t > pl->GetTimeStamp())
1925 pl->SetTimeStamp(t);
1926 UnloadPlugin((IPlugin *)pl);
1932 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
1934 List<IPluginsListener *>::iterator iter;
1935 IPluginsListener *pListener;
1936 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1938 pListener = (*iter);
1939 pListener->OnPluginPauseChange(pl, paused);
1943 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
1945 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
1950 FakeNative *pNative = new FakeNative;
1952 pNative->func = g_pVM->CreateFakeNative(func, pNative);
1959 pNative->call = pFunction;
1960 pNative->name.assign(name);
1961 pNative->ctx = pFunction->GetParentContext();
1963 m_Natives.push_back(pNative);
1964 sm_trie_insert(m_pNativeLookup, name,pNative);
1966 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
1967 pPlugin->m_fakeNatives.push_back(pNative);
1972 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
1974 List<CPlugin *>::iterator iter;
1976 IPluginFunction *pFunction;
1978 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
1982 if (pPlugin->GetStatus() <= Plugin_Paused)
1984 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
1988 pForward->AddFunction(pFunction);
1994 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
1996 if (pToken->type != g_PluginIdent)
2001 return (CPlugin *)(pToken->ptr);
2004 void CPluginManager::ExecAndGenPluginConfs()
2006 List<CPlugin *>::iterator iter;