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 m_IsInAskPluginLoad = true;
361 pFunction->PushCell(m_handle);
362 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
363 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
364 pFunction->PushCell(maxlength);
365 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
367 m_IsInAskPluginLoad = false;
371 m_IsInAskPluginLoad = false;
373 if (!result || m_status != Plugin_Loaded)
381 const sp_plugin_t *CPlugin::GetPluginStructure()
386 IPluginContext *CPlugin::GetBaseContext()
391 sp_context_t *CPlugin::GetContext()
396 const char *CPlugin::GetFilename()
401 PluginType CPlugin::GetType()
406 const sm_plugininfo_t *CPlugin::GetPublicInfo()
411 unsigned int CPlugin::GetSerial()
416 PluginStatus CPlugin::GetStatus()
421 bool CPlugin::IsDebugging()
428 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
431 bool CPlugin::SetPauseState(bool paused)
433 if (paused && GetStatus() != Plugin_Paused)
436 } else if (!paused && GetStatus() != Plugin_Running) {
440 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
444 pFunction->PushCell(paused ? 1 : 0);
445 pFunction->Execute(&result);
450 m_status = Plugin_Paused;
451 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
453 m_status = Plugin_Running;
454 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
457 g_PluginSys._SetPauseState(this, paused);
462 IdentityToken_t *CPlugin::GetIdentity()
467 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
475 snprintf(error, maxlength, "Plugin is not runnable.");
480 if (debug && IsDebugging())
484 snprintf(error, maxlength, "Plugin is already in debug mode.");
487 } else if (!debug && !IsDebugging()) {
490 snprintf(error, maxlength, "Plugins is already in production mode.");
495 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
496 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
500 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
505 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
509 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
510 new_ctx->hp = m_ctx.ctx->hp;
511 new_ctx->sp = m_ctx.ctx->sp;
512 new_ctx->frm = m_ctx.ctx->frm;
513 new_ctx->dbreak = m_ctx.ctx->dbreak;
514 new_ctx->context = m_ctx.ctx->context;
515 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
517 uint32_t nativeCount = m_plugin->info.natives_num;
518 for (uint32_t i=0; i<nativeCount; i++)
520 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
521 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
524 g_pVM->FreeContext(m_ctx.ctx);
526 m_ctx.base->SetContext(new_ctx);
532 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
540 bool CPlugin::IsRunnable()
542 return (m_status <= Plugin_Paused) ? true : false;
545 time_t CPlugin::GetFileTimeStamp()
547 char path[PLATFORM_MAX_PATH];
548 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
549 #ifdef PLATFORM_WINDOWS
551 if (_stat(path, &s) != 0)
552 #elif defined PLATFORM_POSIX
554 if (stat(path, &s) != 0)
563 time_t CPlugin::GetTimeStamp()
568 void CPlugin::SetTimeStamp(time_t t)
573 void CPlugin::AddLangFile(unsigned int index)
575 m_PhraseFiles.push_back(index);
578 size_t CPlugin::GetLangFileCount()
580 return m_PhraseFiles.size();
583 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
585 return m_PhraseFiles.at(index);
588 void CPlugin::DependencyDropped(CPlugin *pOwner)
595 List<FakeNative *>::iterator iter;
599 unsigned int unbound = 0;
601 for (iter = pOwner->m_fakeNatives.begin();
602 iter != pOwner->m_fakeNatives.end();
606 /* Find this native! */
607 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
612 m_ctx.base->GetNativeByIndex(idx, &native);
614 native->status = SP_NATIVE_UNBOUND;
618 /* :IDEA: in the future, add native trapping? */
621 m_FakeNativesMissing = true;
622 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
625 m_dependsOn.remove(pOwner);
628 unsigned int CPlugin::GetConfigCount()
630 return (unsigned int)m_configs.size();
633 AutoConfig *CPlugin::GetConfig(unsigned int i)
635 if (i >= GetConfigCount())
643 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
645 AutoConfig *c = new AutoConfig;
649 c->create = autoCreate;
651 m_configs.push_back(c);
658 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
664 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
669 bool CPluginManager::CPluginIterator::MorePlugins()
671 return (current != mylist->end());
674 void CPluginManager::CPluginIterator::NextPlugin()
679 void CPluginManager::CPluginIterator::Release()
681 g_PluginSys.ReleaseIterator(this);
684 CPluginManager::CPluginIterator::~CPluginIterator()
688 void CPluginManager::CPluginIterator::Reset()
690 current = mylist->begin();
697 CPluginManager::CPluginManager()
699 m_LoadLookup = sm_trie_create();
700 m_AllPluginsLoaded = false;
702 m_pNativeLookup = sm_trie_create();
705 CPluginManager::~CPluginManager()
708 * Ignore the fact that there might be plugins in the cache.
709 * This usually means that Core is not being unloaded properly, and everything
710 * will crash anyway. YAY
712 sm_trie_destroy(m_LoadLookup);
713 sm_trie_destroy(m_pNativeLookup);
715 CStack<CPluginManager::CPluginIterator *>::iterator iter;
716 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
723 void CPluginManager::Shutdown()
725 List<CPlugin *>::iterator iter;
727 while ((iter = m_plugins.begin()) != m_plugins.end())
733 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
735 /* First read in the database of plugin settings */
737 unsigned int line, col;
738 m_AllPluginsLoaded = false;
739 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
741 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
742 const char *err_msg = g_TextParser.GetSMCErrorString(err);
745 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
749 LoadPluginsFromDir(basedir, NULL);
752 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
754 char base_path[PLATFORM_MAX_PATH];
756 /* Form the current path to start reading from */
757 if (localpath == NULL)
759 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
761 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
764 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
769 g_LibSys.GetPlatformError(error, sizeof(error));
770 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
771 g_Logger.LogError("[SM] Platform returned error: %s", error);
775 while (dir->MoreFiles())
777 if (dir->IsEntryDirectory()
778 && (strcmp(dir->GetEntryName(), ".") != 0)
779 && (strcmp(dir->GetEntryName(), "..") != 0)
780 && (strcmp(dir->GetEntryName(), "disabled") != 0)
781 && (strcmp(dir->GetEntryName(), "optional") != 0))
783 char new_local[PLATFORM_MAX_PATH];
784 if (localpath == NULL)
786 /* If no path yet, don't add a former slash */
787 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
789 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
791 LoadPluginsFromDir(basedir, new_local);
792 } else if (dir->IsEntryFile()) {
793 const char *name = dir->GetEntryName();
794 size_t len = strlen(name);
796 && strcmp(&name[len-4], ".smx") == 0)
798 /* If the filename matches, load the plugin */
799 char plugin[PLATFORM_MAX_PATH];
800 if (localpath == NULL)
802 snprintf(plugin, sizeof(plugin), "%s", name);
804 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
806 LoadAutoPlugin(plugin);
811 g_LibSys.CloseDirectory(dir);
814 //well i have discovered that gabe newell is very fat, so i wrote this comment now
815 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
818 * Does this plugin already exist?
821 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
823 /* Check to see if we should try reloading it */
824 if (pPlugin->GetStatus() == Plugin_BadLoad
825 || pPlugin->GetStatus() == Plugin_Error
826 || pPlugin->GetStatus() == Plugin_Failed)
828 UnloadPlugin(pPlugin);
834 return LoadRes_AlreadyLoaded;
838 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
840 assert(pPlugin != NULL);
842 pPlugin->m_type = PluginType_MapUpdated;
844 ICompilation *co = NULL;
846 if (pPlugin->m_status == Plugin_Uncompiled)
848 co = pPlugin->StartMyCompile(g_pVM);
851 PluginSettings *pset;
852 unsigned int setcount = m_PluginInfo.GetSettingsNum();
853 for (unsigned int i=0; i<setcount; i++)
855 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
859 pPlugin->m_type = pset->type_val;
862 for (unsigned int j=0; j<pset->opts_num; j++)
864 const char *key, *val;
865 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
870 if (!g_pVM->SetCompilationOption(co, key, val))
874 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
876 pPlugin->CancelMyCompile();
884 /* Do the actual compiling */
887 pPlugin->FinishMyCompile(error, maxlength);
892 if (pPlugin->GetStatus() == Plugin_Created)
894 AddCoreNativesToPlugin(pPlugin);
895 pPlugin->InitIdentity();
896 if (pPlugin->Call_AskPluginLoad(error, maxlength))
898 /* Autoload any modules */
899 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
903 /* Save the time stamp */
904 time_t t = pPlugin->GetFileTimeStamp();
905 pPlugin->SetTimeStamp(t);
912 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
915 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
921 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
927 if (res == LoadRes_AlreadyLoaded)
935 /* Run second pass if we need to */
936 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
938 if (!RunSecondPass(pl, error, maxlength))
948 void CPluginManager::LoadAutoPlugin(const char *plugin)
952 char error[255] = "Unknown error";
954 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
956 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
957 pl->SetErrorState(Plugin_Failed, "%s", error);
960 if (res == LoadRes_Successful)
966 void CPluginManager::AddPlugin(CPlugin *pPlugin)
968 List<IPluginsListener *>::iterator iter;
969 IPluginsListener *pListener;
971 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
974 pListener->OnPluginCreated(pPlugin);
977 m_plugins.push_back(pPlugin);
978 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
981 void CPluginManager::LoadAll_SecondPass()
983 List<CPlugin *>::iterator iter;
987 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
990 if (pPlugin->GetStatus() == Plugin_Loaded)
993 if (!RunSecondPass(pPlugin, error, sizeof(error)))
995 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
996 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1001 m_AllPluginsLoaded = true;
1004 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1006 /* Find any extensions this plugin needs */
1015 IPluginContext *pBase = pPlugin->GetBaseContext();
1016 uint32_t num = pBase->GetPubVarsNum();
1017 sp_pubvar_t *pubvar;
1019 char path[PLATFORM_MAX_PATH];
1021 for (uint32_t i=0; i<num; i++)
1023 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1027 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1029 ext = (_ext *)pubvar->offs;
1030 if (!ext->required && !ext->autoload)
1034 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1038 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1044 /* Attempt to auto-load if necessary */
1047 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1048 g_Extensions.LoadAutoExtension(path);
1050 } else if (pass == 2) {
1051 /* Is this required? */
1054 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1055 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1057 pExt = g_Extensions.FindExtensionByName(name);
1059 /* :TODO: should we bind to unloaded extensions?
1060 * Currently the extension manager will ignore this.
1062 if (!pExt || !pExt->IsRunning(NULL, 0))
1066 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1070 g_Extensions.BindChildPlugin(pExt, pPlugin);
1080 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1082 /* Second pass for extension requirements */
1083 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1088 /* Bind all extra natives */
1089 g_Extensions.BindAllNativesToPlugin(pPlugin);
1090 AddFakeNativesToPlugin(pPlugin);
1092 /* Find any unbound natives
1093 * Right now, these are not allowed
1095 IPluginContext *pContext = pPlugin->GetBaseContext();
1096 uint32_t num = pContext->GetNativesNum();
1097 sp_native_t *native;
1098 for (unsigned int i=0; i<num; i++)
1100 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1104 if (native->status == SP_NATIVE_UNBOUND
1105 && native->name[0] != '@'
1106 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1110 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1116 /* Finish by telling all listeners */
1117 List<IPluginsListener *>::iterator iter;
1118 IPluginsListener *pListener;
1119 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1121 pListener = (*iter);
1122 pListener->OnPluginLoaded(pPlugin);
1125 /* Tell this plugin to finish initializing itself */
1126 pPlugin->Call_OnPluginStart();
1128 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1129 if (pPlugin->GetStatus() >= Plugin_Paused && pPlugin->m_fakeNatives.size())
1131 List<CPlugin *>::iterator pl_iter;
1133 for (pl_iter = m_plugins.begin();
1134 pl_iter != m_plugins.end();
1137 pOther = (*pl_iter);
1138 if (pOther->GetStatus() == Plugin_Error
1139 && pOther->m_FakeNativesMissing)
1141 TryRefreshNatives(pOther);
1149 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1151 List<sp_nativeinfo_t *>::iterator iter;
1153 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1155 sp_nativeinfo_t *natives = (*iter);
1156 IPluginContext *ctx = pPlugin->GetBaseContext();
1158 /* Attempt to bind every native! */
1159 while (natives[i].func != NULL)
1161 ctx->BindNative(&natives[i++]);
1166 void CPluginManager::TryRefreshNatives(CPlugin *pPlugin)
1168 assert(pPlugin->GetBaseContext() != NULL);
1170 AddFakeNativesToPlugin(pPlugin);
1172 /* Find any unbound natives
1173 * Right now, these are not allowed
1175 IPluginContext *pContext = pPlugin->GetBaseContext();
1176 uint32_t num = pContext->GetNativesNum();
1177 sp_native_t *native;
1178 for (unsigned int i=0; i<num; i++)
1180 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1184 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1186 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1191 /* If we got here, all natives are okay again! */
1192 pPlugin->m_status = Plugin_Running;
1193 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1195 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1196 _SetPauseState(pPlugin, false);
1200 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1202 IPluginContext *pContext = pPlugin->GetBaseContext();
1203 sp_nativeinfo_t native;
1205 List<FakeNative *>::iterator iter;
1206 FakeNative *pNative;
1208 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1211 ctx = pNative->ctx->GetContext();
1212 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1214 /* Ignore natives in paused plugins */
1217 native.name = pNative->name.c_str();
1218 native.func = pNative->func;
1219 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1222 pContext->FindNativeByName(native.name, &idx);
1223 if (!(pPlugin->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL))
1227 /* Add us as a dependency, but we're careful not to do this circularly! */
1228 if (pNative->ctx != pContext)
1230 CPlugin *pOther = GetPluginByCtx(ctx);
1231 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1233 pOther->m_dependents.push_back(pPlugin);
1235 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1237 pPlugin->m_dependsOn.push_back(pOther);
1244 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1246 CPlugin *pPlugin = (CPlugin *)plugin;
1248 /* This prevents removal during insertion or anything else weird */
1249 if (m_plugins.find(pPlugin) == m_plugins.end())
1254 /* Remove us from the lookup table and linked list */
1255 m_plugins.remove(pPlugin);
1256 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1258 /* Go through all dependent plugins and tell them this plugin is now gone */
1259 List<CPlugin *>::iterator pl_iter;
1261 for (pl_iter = pPlugin->m_dependents.begin();
1262 pl_iter != pPlugin->m_dependents.end();
1265 pOther = (*pl_iter);
1266 pOther->DependencyDropped(pPlugin);
1269 /* Tell everyone we depend on that we no longer exist */
1270 for (pl_iter = pPlugin->m_dependsOn.begin();
1271 pl_iter != pPlugin->m_dependsOn.end();
1274 pOther = (*pl_iter);
1275 pOther->m_dependents.remove(pPlugin);
1278 /* Remove all of our native functions */
1279 List<FakeNative *>::iterator fn_iter;
1280 FakeNative *pNative;
1281 for (fn_iter = pPlugin->m_fakeNatives.begin();
1282 fn_iter != pPlugin->m_fakeNatives.end();
1285 pNative = (*fn_iter);
1286 m_Natives.remove(pNative);
1287 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1288 g_pVM->DestroyFakeNative(pNative->func);
1292 List<IPluginsListener *>::iterator iter;
1293 IPluginsListener *pListener;
1295 if (pPlugin->GetStatus() <= Plugin_Error)
1297 /* Notify listeners of unloading */
1298 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1300 pListener = (*iter);
1301 pListener->OnPluginUnloaded(pPlugin);
1304 pPlugin->Call_OnPluginEnd();
1307 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1309 /* Notify listeners of destruction */
1310 pListener = (*iter);
1311 pListener->OnPluginDestroyed(pPlugin);
1314 /* Tell the plugin to delete itself */
1320 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1322 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1326 unsigned int CPluginManager::GetPluginCount()
1328 return m_plugins.size();
1331 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1333 m_listeners.push_back(listener);
1336 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1338 m_listeners.remove(listener);
1341 IPluginIterator *CPluginManager::GetPluginIterator()
1343 if (m_iters.empty())
1345 return new CPluginIterator(&m_plugins);
1347 CPluginIterator *iter = m_iters.front();
1354 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1359 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1361 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1362 size_t alias_len = 0;
1363 size_t local_len = 0;
1365 const char *ptr = alias;
1366 unsigned int alias_explicit_paths = 0;
1367 unsigned int alias_path_end = 0;
1368 while (*ptr != '\0')
1370 if (*ptr == '\\' || *ptr == '/')
1372 alias_explicit_paths++;
1373 alias_path_end = alias_len;
1379 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1381 /* Trailing slash is totally invalid here */
1386 unsigned int local_explicit_paths = 0;
1387 unsigned int local_path_end = 0;
1388 while (*ptr != '\0')
1390 if (*ptr == '\\' || *ptr == '/')
1392 local_explicit_paths++;
1393 local_path_end = local_len;
1399 /* If the alias has more explicit paths than the real path,
1400 * no match will be possible.
1402 if (alias_explicit_paths > local_explicit_paths)
1407 if (alias_explicit_paths)
1409 /* We need to find if the paths match now. For example, these should all match:
1411 * csdm optional/csdm
1412 * csdm/ban optional/crab/csdm/ban
1414 const char *aliasptr = alias;
1415 const char *localptr = localpath;
1419 if (*aliasptr != *localptr)
1421 /* We have to knock one path off */
1422 local_explicit_paths--;
1423 if (alias_explicit_paths > local_explicit_paths)
1425 /* Skip out if we're gonna have an impossible match */
1428 /* Eat up localptr tokens until we get a result */
1429 while (((localptr - localpath) < (int)local_path_end)
1431 && *localptr != '\\')
1435 /* Check if we hit the end of our searchable area.
1436 * This probably isn't possible because of the path
1437 * count check, but it's a good idea anyway.
1439 if ((localptr - localpath) >= (int)local_path_end)
1443 /* Consume the slash token */
1446 /* Reset the alias pointer so we can continue consuming */
1452 * This is safe because if localptr terminates early, aliasptr will too
1456 /* We should never reach the end of the string because of this check. */
1457 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1458 bool localend = (localptr - localpath) > (int)local_path_end;
1459 if (aliasend || localend)
1461 if (aliasend && localend)
1463 /* we matched, and we can break out now */
1467 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1472 /* If we got here, it's safe to compare the next two tokens */
1473 if (*localptr != *aliasptr)
1484 /* If we got here, it's time to compare filenames */
1485 const char *aliasptr = alias;
1486 const char *localptr = localpath;
1488 if (alias_explicit_paths)
1490 aliasptr = &alias[alias_path_end + 1];
1493 if (local_explicit_paths)
1495 localptr = &localpath[local_path_end + 1];
1500 if (*aliasptr == '*')
1502 /* First, see if this is the last character */
1503 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1505 /* If so, there's no need to match anything else */
1508 /* Otherwise, we need to search for an appropriate matching sequence in local.
1509 * Note that we only need to search up to the next asterisk.
1513 const char *local_orig = localptr;
1517 while (*aliasptr != '\0' && *aliasptr != '*')
1519 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1520 if (*aliasptr != *localptr)
1530 /* If we didn't get a match, we need to advance the search stream.
1531 * This will let us skip tokens while still searching for another match.
1533 localptr = ++local_orig;
1534 /* Make sure we don't go out of bounds */
1535 if (*localptr == '\0')
1546 /* If we got a match, move on to the next token */
1549 } else if (*aliasptr == '\0') {
1550 if (*localptr == '\0'
1552 strcmp(localptr, ".smx") == 0)
1558 } else if (*aliasptr != *localptr) {
1568 bool CPluginManager::IsLateLoadTime() const
1570 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1573 void CPluginManager::OnSourceModAllInitialized()
1575 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1578 g_HandleSys.InitAccessDefaults(NULL, &sec);
1580 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1581 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1583 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1584 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1586 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1588 g_ShareSys.AddInterface(NULL, this);
1591 void CPluginManager::OnSourceModShutdown()
1593 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1595 List<CPlugin *>::iterator iter;
1596 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1598 UnloadPlugin((*iter));
1601 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1602 g_ShareSys.DestroyIdentType(g_PluginIdent);
1603 g_ShareSys.DestroyIdentity(m_MyIdent);
1606 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1608 /* We don't care about the internal object, actually */
1611 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1613 m_natives.push_back(natives);
1616 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1624 sec.pIdentity = m_MyIdent;
1626 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1639 CPlugin *CPluginManager::GetPluginByOrder(int num)
1641 if (num < 1 || num > (int)GetPluginCount())
1649 IPluginIterator *iter = GetPluginIterator();
1650 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1652 pl = (CPlugin *)(iter->GetPlugin());
1658 const char *CPluginManager::GetStatusText(PluginStatus st)
1662 case Plugin_Running:
1668 case Plugin_Uncompiled:
1669 return "Uncompiled";
1670 case Plugin_BadLoad:
1680 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1684 const char *cmd = g_RootMenu.GetArgument(2);
1685 if (strcmp(cmd, "list") == 0)
1688 unsigned int id = 1;
1689 int plnum = GetPluginCount();
1693 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1696 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1699 IPluginIterator *iter = GetPluginIterator();
1700 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1702 IPlugin *pl = iter->GetPlugin();
1703 assert(pl->GetStatus() != Plugin_Created);
1705 const sm_plugininfo_t *info = pl->GetPublicInfo();
1706 if (pl->GetStatus() != Plugin_Running)
1708 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1710 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1712 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1713 if (IS_STR_FILLED(info->version))
1715 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1717 if (IS_STR_FILLED(info->author))
1719 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1721 g_RootMenu.ConsolePrint("%s", buffer);
1726 } else if (strcmp(cmd, "load") == 0) {
1729 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1735 const char *filename = g_RootMenu.GetArgument(3);
1737 char pluginfile[256];
1738 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1739 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1741 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1745 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1751 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1753 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
1757 } else if (strcmp(cmd, "unload") == 0) {
1760 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1765 int num = atoi(g_RootMenu.GetArgument(3));
1766 if (num < 1 || num > (int)GetPluginCount())
1768 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1772 IPluginIterator *iter = GetPluginIterator();
1773 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1775 IPlugin *pl = iter->GetPlugin();
1777 char name[PLATFORM_MAX_PATH];
1778 const sm_plugininfo_t *info = pl->GetPublicInfo();
1779 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1781 if (UnloadPlugin(pl))
1783 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1785 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1790 } else if (strcmp(cmd, "info") == 0) {
1793 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1797 int num = atoi(g_RootMenu.GetArgument(3));
1798 if (num < 1 || num > (int)GetPluginCount())
1800 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1804 CPlugin *pl = GetPluginByOrder(num);
1805 const sm_plugininfo_t *info = pl->GetPublicInfo();
1807 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1808 if (pl->GetStatus() <= Plugin_Error)
1810 if (IS_STR_FILLED(info->name))
1812 if (IS_STR_FILLED(info->description))
1814 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1816 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1819 if (IS_STR_FILLED(info->author))
1821 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1823 if (IS_STR_FILLED(info->version))
1825 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1827 if (IS_STR_FILLED(info->url))
1829 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1831 if (pl->GetStatus() == Plugin_Error)
1833 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
1835 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
1836 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
1838 const char *typestr = "";
1839 switch (pl->GetType())
1841 case PluginType_MapUpdated:
1842 typestr = "Map Change if Updated";
1844 case PluginType_MapOnly:
1845 typestr = "Map Change";
1847 case PluginType_Private:
1848 case PluginType_Global:
1853 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
1856 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
1857 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
1858 info->name ? info->name : "<none>",
1859 info->version ? info->version : "<none>");
1860 if (IS_STR_FILLED(info->url))
1862 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
1867 } else if (strcmp(cmd, "debug") == 0) {
1870 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
1874 int num = atoi(g_RootMenu.GetArgument(3));
1875 if (num < 1 || num > (int)GetPluginCount())
1877 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1882 const char *mode = g_RootMenu.GetArgument(4);
1883 if ((res=strcmp("on", mode)) && strcmp("off", mode))
1885 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
1897 CPlugin *pl = GetPluginByOrder(num);
1898 if (debug && pl->IsDebugging())
1900 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
1902 } else if (!debug && !pl->IsDebugging()) {
1903 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
1908 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
1910 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
1913 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
1914 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
1920 /* Draw the main menu */
1921 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
1922 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
1923 g_RootMenu.DrawGenericOption("load", "Load a plugin");
1924 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
1925 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
1926 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
1929 void CPluginManager::ReloadOrUnloadPlugins()
1931 List<CPlugin *>::iterator iter;
1932 List<CPlugin *> tmp_list = m_plugins;
1936 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
1939 if (pl->GetType() == PluginType_MapOnly)
1941 UnloadPlugin((IPlugin *)pl);
1942 } else if (pl->GetType() == PluginType_MapUpdated) {
1943 t = pl->GetFileTimeStamp();
1944 if (!t || t > pl->GetTimeStamp())
1946 pl->SetTimeStamp(t);
1947 UnloadPlugin((IPlugin *)pl);
1953 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
1955 List<IPluginsListener *>::iterator iter;
1956 IPluginsListener *pListener;
1957 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1959 pListener = (*iter);
1960 pListener->OnPluginPauseChange(pl, paused);
1964 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
1966 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
1971 FakeNative *pNative = new FakeNative;
1973 pNative->func = g_pVM->CreateFakeNative(func, pNative);
1980 pNative->call = pFunction;
1981 pNative->name.assign(name);
1982 pNative->ctx = pFunction->GetParentContext();
1984 m_Natives.push_back(pNative);
1985 sm_trie_insert(m_pNativeLookup, name,pNative);
1987 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
1988 pPlugin->m_fakeNatives.push_back(pNative);
1993 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
1995 List<CPlugin *>::iterator iter;
1997 IPluginFunction *pFunction;
1999 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2003 if (pPlugin->GetStatus() <= Plugin_Paused)
2005 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2009 pForward->AddFunction(pFunction);
2015 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2017 if (pToken->type != g_PluginIdent)
2022 return (CPlugin *)(pToken->ptr);
2025 void CPluginManager::ExecAndGenPluginConfs()
2027 List<CPlugin *>::iterator iter;