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;
50 m_LibraryMissing = false;
58 sec.pOwner = g_PluginSys.GetIdentity();
59 sec.pIdentity = sec.pOwner;
61 g_HandleSys.FreeHandle(m_handle, &sec);
62 g_ShareSys.DestroyIdentity(m_ident);
72 m_ctx.vm->FreeContext(m_ctx.ctx);
77 m_ctx.vm->AbortCompilation(m_ctx.co);
83 g_pSourcePawn->FreeFromMemory(m_plugin);
88 sm_trie_destroy(m_pProps);
90 for (size_t i=0; i<m_configs.size(); i++)
97 void CPlugin::InitIdentity()
101 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
102 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
103 m_ctx.base->SetIdentity(m_ident);
107 Handle_t CPlugin::GetMyHandle()
112 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
114 char fullpath[PLATFORM_MAX_PATH];
115 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
116 FILE *fp = fopen(fullpath, "rb");
118 CPlugin *pPlugin = new CPlugin(file);
124 snprintf(error, maxlength, "Unable to open file");
126 pPlugin->m_status = Plugin_BadLoad;
131 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
137 snprintf(error, maxlength, "Error %d while parsing plugin", err);
139 pPlugin->m_status = Plugin_BadLoad;
145 pPlugin->m_plugin = pl;
150 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
152 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
154 if (exists && remove)
156 sm_trie_delete(m_pProps, prop);
162 bool CPlugin::SetProperty(const char *prop, void *ptr)
164 return sm_trie_insert(m_pProps, prop, ptr);
167 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
174 /* :NOTICE: We will eventually need to change these natives
175 * for swapping in new contexts
177 if (m_ctx.co || m_ctx.ctx)
182 m_status = Plugin_Uncompiled;
185 m_ctx.co = vm->StartCompilation(m_plugin);
190 void CPlugin::CancelMyCompile()
197 m_ctx.vm->AbortCompilation(m_ctx.co);
202 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
210 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
213 memset(&m_ctx, 0, sizeof(m_ctx));
216 snprintf(error, maxlength, "JIT failed to compile (error %d)", err);
221 m_ctx.base = new BaseContext(m_ctx.ctx);
222 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
224 m_status = Plugin_Created;
232 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
234 PluginStatus old_status = m_status;
237 if (old_status == Plugin_Running)
239 /* Tell everyone we're now paused */
240 g_PluginSys._SetPauseState(this, true);
244 va_start(ap, error_fmt);
245 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
250 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
254 void CPlugin::UpdateInfo()
256 /* Now grab the info */
258 IPluginContext *base = GetBaseContext();
259 int err = base->FindPubvarByName("myinfo", &idx);
261 memset(&m_info, 0, sizeof(m_info));
263 if (err == SP_ERROR_NONE)
265 struct sm_plugininfo_c_t
273 sm_plugininfo_c_t *cinfo;
276 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
277 base->LocalToString(cinfo->name, (char **)&m_info.name);
278 base->LocalToString(cinfo->description, (char **)&m_info.description);
279 base->LocalToString(cinfo->author, (char **)&m_info.author);
280 base->LocalToString(cinfo->url, (char **)&m_info.url);
281 base->LocalToString(cinfo->version, (char **)&m_info.version);
284 m_info.author = m_info.author ? m_info.author : "";
285 m_info.description = m_info.description ? m_info.description : "";
286 m_info.name = m_info.name ? m_info.name : "";
287 m_info.url = m_info.url ? m_info.url : "";
288 m_info.version = m_info.version ? m_info.version : "";
291 void CPlugin::Call_OnPluginStart()
293 if (m_status != Plugin_Loaded)
298 m_status = Plugin_Running;
301 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
308 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
310 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
314 if ((pFunction = m_ctx.base->GetFunctionByName("OnMapStart")) != NULL)
316 pFunction->Execute(NULL);
319 if (SM_AreConfigsExecuted())
321 SM_ExecuteForPlugin(GetBaseContext());
326 void CPlugin::Call_OnPluginEnd()
328 if (m_status > Plugin_Paused)
334 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
340 pFunction->Execute(&result);
343 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
345 if (m_status != Plugin_Created)
350 m_status = Plugin_Loaded;
354 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
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)
370 if (!result || m_status != Plugin_Loaded)
378 const sp_plugin_t *CPlugin::GetPluginStructure()
383 IPluginContext *CPlugin::GetBaseContext()
388 sp_context_t *CPlugin::GetContext()
393 const char *CPlugin::GetFilename()
398 PluginType CPlugin::GetType()
403 const sm_plugininfo_t *CPlugin::GetPublicInfo()
408 unsigned int CPlugin::GetSerial()
413 PluginStatus CPlugin::GetStatus()
418 bool CPlugin::IsDebugging()
425 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
428 bool CPlugin::SetPauseState(bool paused)
430 if (paused && GetStatus() != Plugin_Paused)
433 } else if (!paused && GetStatus() != Plugin_Running) {
437 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
441 pFunction->PushCell(paused ? 1 : 0);
442 pFunction->Execute(&result);
447 m_status = Plugin_Paused;
448 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
450 m_status = Plugin_Running;
451 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
454 g_PluginSys._SetPauseState(this, paused);
459 IdentityToken_t *CPlugin::GetIdentity()
464 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
472 snprintf(error, maxlength, "Plugin is not runnable.");
477 if (debug && IsDebugging())
481 snprintf(error, maxlength, "Plugin is already in debug mode.");
484 } else if (!debug && !IsDebugging()) {
487 snprintf(error, maxlength, "Plugins is already in production mode.");
492 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
493 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
497 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
502 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
506 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
507 new_ctx->hp = m_ctx.ctx->hp;
508 new_ctx->sp = m_ctx.ctx->sp;
509 new_ctx->frm = m_ctx.ctx->frm;
510 new_ctx->dbreak = m_ctx.ctx->dbreak;
511 new_ctx->context = m_ctx.ctx->context;
512 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
514 uint32_t nativeCount = m_plugin->info.natives_num;
515 for (uint32_t i=0; i<nativeCount; i++)
517 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
518 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
521 g_pVM->FreeContext(m_ctx.ctx);
523 m_ctx.base->SetContext(new_ctx);
529 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
537 bool CPlugin::IsRunnable()
539 return (m_status <= Plugin_Paused) ? true : false;
542 time_t CPlugin::GetFileTimeStamp()
544 char path[PLATFORM_MAX_PATH];
545 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
546 #ifdef PLATFORM_WINDOWS
548 if (_stat(path, &s) != 0)
549 #elif defined PLATFORM_POSIX
551 if (stat(path, &s) != 0)
560 time_t CPlugin::GetTimeStamp()
565 void CPlugin::SetTimeStamp(time_t t)
570 void CPlugin::AddLangFile(unsigned int index)
572 m_PhraseFiles.push_back(index);
575 size_t CPlugin::GetLangFileCount()
577 return m_PhraseFiles.size();
580 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
582 return m_PhraseFiles.at(index);
585 void CPlugin::DependencyDropped(CPlugin *pOwner)
592 List<String>::iterator reqlib_iter;
593 List<String>::iterator lib_iter;
594 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
596 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
598 if ((*reqlib_iter) == (*lib_iter))
600 m_LibraryMissing = true;
605 List<FakeNative *>::iterator iter;
609 unsigned int unbound = 0;
611 for (iter = pOwner->m_fakeNatives.begin();
612 iter != pOwner->m_fakeNatives.end();
616 /* Find this native! */
617 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
622 m_ctx.base->GetNativeByIndex(idx, &native);
624 native->status = SP_NATIVE_UNBOUND;
630 m_FakeNativesMissing = true;
633 /* :IDEA: in the future, add native trapping? */
634 if (m_FakeNativesMissing || m_LibraryMissing)
636 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
639 m_dependsOn.remove(pOwner);
642 unsigned int CPlugin::GetConfigCount()
644 return (unsigned int)m_configs.size();
647 AutoConfig *CPlugin::GetConfig(unsigned int i)
649 if (i >= GetConfigCount())
657 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
659 AutoConfig *c = new AutoConfig;
663 c->create = autoCreate;
665 m_configs.push_back(c);
672 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
678 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
683 bool CPluginManager::CPluginIterator::MorePlugins()
685 return (current != mylist->end());
688 void CPluginManager::CPluginIterator::NextPlugin()
693 void CPluginManager::CPluginIterator::Release()
695 g_PluginSys.ReleaseIterator(this);
698 CPluginManager::CPluginIterator::~CPluginIterator()
702 void CPluginManager::CPluginIterator::Reset()
704 current = mylist->begin();
711 CPluginManager::CPluginManager()
713 m_LoadLookup = sm_trie_create();
714 m_AllPluginsLoaded = false;
716 m_pNativeLookup = sm_trie_create();
719 CPluginManager::~CPluginManager()
722 * Ignore the fact that there might be plugins in the cache.
723 * This usually means that Core is not being unloaded properly, and everything
724 * will crash anyway. YAY
726 sm_trie_destroy(m_LoadLookup);
727 sm_trie_destroy(m_pNativeLookup);
729 CStack<CPluginManager::CPluginIterator *>::iterator iter;
730 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
737 void CPluginManager::Shutdown()
739 List<CPlugin *>::iterator iter;
741 while ((iter = m_plugins.begin()) != m_plugins.end())
747 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
749 /* First read in the database of plugin settings */
751 unsigned int line, col;
752 m_AllPluginsLoaded = false;
753 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
755 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
756 const char *err_msg = g_TextParser.GetSMCErrorString(err);
759 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
763 LoadPluginsFromDir(basedir, NULL);
766 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
768 char base_path[PLATFORM_MAX_PATH];
770 /* Form the current path to start reading from */
771 if (localpath == NULL)
773 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
775 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
778 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
783 g_LibSys.GetPlatformError(error, sizeof(error));
784 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
785 g_Logger.LogError("[SM] Platform returned error: %s", error);
789 while (dir->MoreFiles())
791 if (dir->IsEntryDirectory()
792 && (strcmp(dir->GetEntryName(), ".") != 0)
793 && (strcmp(dir->GetEntryName(), "..") != 0)
794 && (strcmp(dir->GetEntryName(), "disabled") != 0)
795 && (strcmp(dir->GetEntryName(), "optional") != 0))
797 char new_local[PLATFORM_MAX_PATH];
798 if (localpath == NULL)
800 /* If no path yet, don't add a former slash */
801 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
803 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
805 LoadPluginsFromDir(basedir, new_local);
806 } else if (dir->IsEntryFile()) {
807 const char *name = dir->GetEntryName();
808 size_t len = strlen(name);
810 && strcmp(&name[len-4], ".smx") == 0)
812 /* If the filename matches, load the plugin */
813 char plugin[PLATFORM_MAX_PATH];
814 if (localpath == NULL)
816 snprintf(plugin, sizeof(plugin), "%s", name);
818 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
820 LoadAutoPlugin(plugin);
825 g_LibSys.CloseDirectory(dir);
828 //well i have discovered that gabe newell is very fat, so i wrote this comment now
829 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
832 * Does this plugin already exist?
835 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
837 /* Check to see if we should try reloading it */
838 if (pPlugin->GetStatus() == Plugin_BadLoad
839 || pPlugin->GetStatus() == Plugin_Error
840 || pPlugin->GetStatus() == Plugin_Failed)
842 UnloadPlugin(pPlugin);
848 return LoadRes_AlreadyLoaded;
852 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
854 assert(pPlugin != NULL);
856 pPlugin->m_type = PluginType_MapUpdated;
858 ICompilation *co = NULL;
860 if (pPlugin->m_status == Plugin_Uncompiled)
862 co = pPlugin->StartMyCompile(g_pVM);
865 PluginSettings *pset;
866 unsigned int setcount = m_PluginInfo.GetSettingsNum();
867 for (unsigned int i=0; i<setcount; i++)
869 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
873 pPlugin->m_type = pset->type_val;
876 for (unsigned int j=0; j<pset->opts_num; j++)
878 const char *key, *val;
879 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
884 if (!g_pVM->SetCompilationOption(co, key, val))
888 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
890 pPlugin->CancelMyCompile();
898 /* Do the actual compiling */
901 pPlugin->FinishMyCompile(error, maxlength);
906 if (pPlugin->GetStatus() == Plugin_Created)
908 AddCoreNativesToPlugin(pPlugin);
909 pPlugin->InitIdentity();
910 if (pPlugin->Call_AskPluginLoad(error, maxlength))
912 /* Autoload any modules */
913 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
917 /* Save the time stamp */
918 time_t t = pPlugin->GetFileTimeStamp();
919 pPlugin->SetTimeStamp(t);
926 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
929 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
935 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
941 if (res == LoadRes_AlreadyLoaded)
949 /* Run second pass if we need to */
950 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
952 if (!RunSecondPass(pl, error, maxlength))
962 void CPluginManager::LoadAutoPlugin(const char *plugin)
966 char error[255] = "Unknown error";
968 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
970 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
971 pl->SetErrorState(Plugin_Failed, "%s", error);
974 if (res == LoadRes_Successful)
980 void CPluginManager::AddPlugin(CPlugin *pPlugin)
982 List<IPluginsListener *>::iterator iter;
983 IPluginsListener *pListener;
985 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
988 pListener->OnPluginCreated(pPlugin);
991 m_plugins.push_back(pPlugin);
992 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
995 void CPluginManager::LoadAll_SecondPass()
997 List<CPlugin *>::iterator iter;
1001 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1004 if (pPlugin->GetStatus() == Plugin_Loaded)
1007 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1009 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1010 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1015 m_AllPluginsLoaded = true;
1018 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1027 IPluginContext *pBase = pPlugin->GetBaseContext();
1028 uint32_t num = pBase->GetPubVarsNum();
1029 sp_pubvar_t *pubvar;
1031 char pathfile[PLATFORM_MAX_PATH];
1033 for (uint32_t i=0; i<num; i++)
1035 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1039 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1041 pl = (_pl *)pubvar->offs;
1042 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1046 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1050 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1051 if (strcmp(pathfile, file) == 0)
1055 if (pl->required == false)
1057 IPluginFunction *pFunc;
1059 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1060 if ((pFunc=pBase->GetFunctionByName(buffer)))
1063 pFunc->Execute(&res);
1064 if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
1068 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1074 /* Check that we aren't registering the same library twice */
1075 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1077 pPlugin->m_RequiredLibs.push_back(name);
1081 List<CPlugin *>::iterator iter;
1084 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1087 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1097 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1108 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1110 /* Find any extensions this plugin needs */
1119 IPluginContext *pBase = pPlugin->GetBaseContext();
1120 uint32_t num = pBase->GetPubVarsNum();
1121 sp_pubvar_t *pubvar;
1123 char path[PLATFORM_MAX_PATH];
1125 for (uint32_t i=0; i<num; i++)
1127 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1131 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1133 ext = (_ext *)pubvar->offs;
1134 if (!ext->required && !ext->autoload)
1138 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1142 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1148 /* Attempt to auto-load if necessary */
1151 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1152 g_Extensions.LoadAutoExtension(path);
1154 } else if (pass == 2) {
1155 /* Is this required? */
1158 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1159 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1161 pExt = g_Extensions.FindExtensionByName(name);
1163 /* :TODO: should we bind to unloaded extensions?
1164 * Currently the extension manager will ignore this.
1166 if (!pExt || !pExt->IsRunning(NULL, 0))
1170 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1174 g_Extensions.BindChildPlugin(pExt, pPlugin);
1184 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1186 /* Second pass for extension requirements */
1187 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1192 /* Bind all extra natives */
1193 g_Extensions.BindAllNativesToPlugin(pPlugin);
1194 AddFakeNativesToPlugin(pPlugin);
1196 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1201 /* Find any unbound natives
1202 * Right now, these are not allowed
1204 IPluginContext *pContext = pPlugin->GetBaseContext();
1205 uint32_t num = pContext->GetNativesNum();
1206 sp_native_t *native;
1207 for (unsigned int i=0; i<num; i++)
1209 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1213 if (native->status == SP_NATIVE_UNBOUND
1214 && native->name[0] != '@'
1215 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1219 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1225 /* Finish by telling all listeners */
1226 List<IPluginsListener *>::iterator iter;
1227 IPluginsListener *pListener;
1228 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1230 pListener = (*iter);
1231 pListener->OnPluginLoaded(pPlugin);
1234 /* Tell this plugin to finish initializing itself */
1235 pPlugin->Call_OnPluginStart();
1237 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1238 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_fakeNatives.size())
1240 List<CPlugin *>::iterator pl_iter;
1242 for (pl_iter = m_plugins.begin();
1243 pl_iter != m_plugins.end();
1246 pOther = (*pl_iter);
1247 if ((pOther->GetStatus() == Plugin_Error
1248 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1249 || pOther->m_FakeNativesMissing)
1251 TryRefreshDependencies(pOther);
1259 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1261 List<sp_nativeinfo_t *>::iterator iter;
1263 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1265 sp_nativeinfo_t *natives = (*iter);
1266 IPluginContext *ctx = pPlugin->GetBaseContext();
1268 /* Attempt to bind every native! */
1269 while (natives[i].func != NULL)
1271 ctx->BindNative(&natives[i++]);
1276 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1278 assert(pPlugin->GetBaseContext() != NULL);
1280 AddFakeNativesToPlugin(pPlugin);
1282 List<String>::iterator lib_iter;
1283 List<String>::iterator req_iter;
1284 List<CPlugin *>::iterator pl_iter;
1286 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1289 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1292 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1294 if ((*req_iter) == (*lib_iter))
1302 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1307 /* Find any unbound natives
1308 * Right now, these are not allowed
1310 IPluginContext *pContext = pPlugin->GetBaseContext();
1311 uint32_t num = pContext->GetNativesNum();
1312 sp_native_t *native;
1313 for (unsigned int i=0; i<num; i++)
1315 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1319 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1321 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1326 if (pPlugin->GetStatus() == Plugin_Error)
1328 /* If we got here, all natives are okay again! */
1329 pPlugin->m_status = Plugin_Running;
1330 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1332 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1333 _SetPauseState(pPlugin, false);
1338 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1340 IPluginContext *pContext = pPlugin->GetBaseContext();
1341 sp_nativeinfo_t native;
1343 List<FakeNative *>::iterator iter;
1344 FakeNative *pNative;
1346 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1349 ctx = pNative->ctx->GetContext();
1350 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1352 /* Ignore natives in paused plugins */
1355 native.name = pNative->name.c_str();
1356 native.func = pNative->func;
1357 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1360 pContext->FindNativeByName(native.name, &idx);
1361 if (pPlugin->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL)
1363 WeakNative wkn(pPlugin, idx);
1364 GetPluginByCtx(ctx)->m_WeakNatives.push_back(wkn);
1367 /* Add us as a dependency, but we're careful not to do this circularly! */
1368 if (pNative->ctx != pContext)
1370 CPlugin *pOther = GetPluginByCtx(ctx);
1371 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1373 pOther->m_dependents.push_back(pPlugin);
1375 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1377 pPlugin->m_dependsOn.push_back(pOther);
1384 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1386 CPlugin *pPlugin = (CPlugin *)plugin;
1388 /* This prevents removal during insertion or anything else weird */
1389 if (m_plugins.find(pPlugin) == m_plugins.end())
1394 /* Remove us from the lookup table and linked list */
1395 m_plugins.remove(pPlugin);
1396 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1398 /* Go through all dependent plugins and tell them this plugin is now gone */
1399 List<CPlugin *>::iterator pl_iter;
1401 for (pl_iter = pPlugin->m_dependents.begin();
1402 pl_iter != pPlugin->m_dependents.end();
1405 pOther = (*pl_iter);
1406 pOther->DependencyDropped(pPlugin);
1409 /* Tell everyone we depend on that we no longer exist */
1410 for (pl_iter = pPlugin->m_dependsOn.begin();
1411 pl_iter != pPlugin->m_dependsOn.end();
1414 pOther = (*pl_iter);
1415 pOther->m_dependents.remove(pPlugin);
1418 /* Remove weak references to us */
1419 for (pl_iter = m_plugins.begin();
1420 pl_iter != m_plugins.end();
1423 pOther = (*pl_iter);
1424 List<WeakNative>::iterator wk_iter = pOther->m_WeakNatives.begin();
1425 while (wk_iter != pOther->m_WeakNatives.end())
1427 if ((*wk_iter).pl == pPlugin)
1429 wk_iter = pOther->m_WeakNatives.erase(wk_iter);
1436 List<IPluginsListener *>::iterator iter;
1437 IPluginsListener *pListener;
1439 if (pPlugin->GetStatus() <= Plugin_Error)
1441 /* Notify listeners of unloading */
1442 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1444 pListener = (*iter);
1445 pListener->OnPluginUnloaded(pPlugin);
1448 pPlugin->Call_OnPluginEnd();
1451 /* Unbound weak natives */
1452 List<WeakNative>::iterator wk_iter;
1453 for (wk_iter=pPlugin->m_WeakNatives.begin(); wk_iter!=pPlugin->m_WeakNatives.end(); wk_iter++)
1455 WeakNative & wkn = (*wk_iter);
1456 sp_context_t *ctx = wkn.pl->GetContext();
1457 ctx->natives[wkn.idx].status = SP_NATIVE_UNBOUND;
1458 wkn.pl->m_FakeNativesMissing = true;
1461 /* Remove all of our native functions */
1462 List<FakeNative *>::iterator fn_iter;
1463 FakeNative *pNative;
1464 for (fn_iter = pPlugin->m_fakeNatives.begin();
1465 fn_iter != pPlugin->m_fakeNatives.end();
1468 pNative = (*fn_iter);
1469 m_Natives.remove(pNative);
1470 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1471 g_pVM->DestroyFakeNative(pNative->func);
1475 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1477 /* Notify listeners of destruction */
1478 pListener = (*iter);
1479 pListener->OnPluginDestroyed(pPlugin);
1482 /* Tell the plugin to delete itself */
1488 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1490 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1494 unsigned int CPluginManager::GetPluginCount()
1496 return m_plugins.size();
1499 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1501 m_listeners.push_back(listener);
1504 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1506 m_listeners.remove(listener);
1509 IPluginIterator *CPluginManager::GetPluginIterator()
1511 if (m_iters.empty())
1513 return new CPluginIterator(&m_plugins);
1515 CPluginIterator *iter = m_iters.front();
1522 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1527 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1529 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1530 size_t alias_len = 0;
1531 size_t local_len = 0;
1533 const char *ptr = alias;
1534 unsigned int alias_explicit_paths = 0;
1535 unsigned int alias_path_end = 0;
1536 while (*ptr != '\0')
1538 if (*ptr == '\\' || *ptr == '/')
1540 alias_explicit_paths++;
1541 alias_path_end = alias_len;
1547 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1549 /* Trailing slash is totally invalid here */
1554 unsigned int local_explicit_paths = 0;
1555 unsigned int local_path_end = 0;
1556 while (*ptr != '\0')
1558 if (*ptr == '\\' || *ptr == '/')
1560 local_explicit_paths++;
1561 local_path_end = local_len;
1567 /* If the alias has more explicit paths than the real path,
1568 * no match will be possible.
1570 if (alias_explicit_paths > local_explicit_paths)
1575 if (alias_explicit_paths)
1577 /* We need to find if the paths match now. For example, these should all match:
1579 * csdm optional/csdm
1580 * csdm/ban optional/crab/csdm/ban
1582 const char *aliasptr = alias;
1583 const char *localptr = localpath;
1587 if (*aliasptr != *localptr)
1589 /* We have to knock one path off */
1590 local_explicit_paths--;
1591 if (alias_explicit_paths > local_explicit_paths)
1593 /* Skip out if we're gonna have an impossible match */
1596 /* Eat up localptr tokens until we get a result */
1597 while (((localptr - localpath) < (int)local_path_end)
1599 && *localptr != '\\')
1603 /* Check if we hit the end of our searchable area.
1604 * This probably isn't possible because of the path
1605 * count check, but it's a good idea anyway.
1607 if ((localptr - localpath) >= (int)local_path_end)
1611 /* Consume the slash token */
1614 /* Reset the alias pointer so we can continue consuming */
1620 * This is safe because if localptr terminates early, aliasptr will too
1624 /* We should never reach the end of the string because of this check. */
1625 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1626 bool localend = (localptr - localpath) > (int)local_path_end;
1627 if (aliasend || localend)
1629 if (aliasend && localend)
1631 /* we matched, and we can break out now */
1635 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1640 /* If we got here, it's safe to compare the next two tokens */
1641 if (*localptr != *aliasptr)
1652 /* If we got here, it's time to compare filenames */
1653 const char *aliasptr = alias;
1654 const char *localptr = localpath;
1656 if (alias_explicit_paths)
1658 aliasptr = &alias[alias_path_end + 1];
1661 if (local_explicit_paths)
1663 localptr = &localpath[local_path_end + 1];
1668 if (*aliasptr == '*')
1670 /* First, see if this is the last character */
1671 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1673 /* If so, there's no need to match anything else */
1676 /* Otherwise, we need to search for an appropriate matching sequence in local.
1677 * Note that we only need to search up to the next asterisk.
1681 const char *local_orig = localptr;
1685 while (*aliasptr != '\0' && *aliasptr != '*')
1687 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1688 if (*aliasptr != *localptr)
1698 /* If we didn't get a match, we need to advance the search stream.
1699 * This will let us skip tokens while still searching for another match.
1701 localptr = ++local_orig;
1702 /* Make sure we don't go out of bounds */
1703 if (*localptr == '\0')
1714 /* If we got a match, move on to the next token */
1717 } else if (*aliasptr == '\0') {
1718 if (*localptr == '\0'
1720 strcmp(localptr, ".smx") == 0)
1726 } else if (*aliasptr != *localptr) {
1736 bool CPluginManager::IsLateLoadTime() const
1738 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1741 void CPluginManager::OnSourceModAllInitialized()
1743 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1746 g_HandleSys.InitAccessDefaults(NULL, &sec);
1748 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1749 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1751 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1752 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1754 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1756 g_ShareSys.AddInterface(NULL, this);
1759 void CPluginManager::OnSourceModShutdown()
1761 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1763 List<CPlugin *>::iterator iter;
1764 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1766 UnloadPlugin((*iter));
1769 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1770 g_ShareSys.DestroyIdentType(g_PluginIdent);
1771 g_ShareSys.DestroyIdentity(m_MyIdent);
1774 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1776 /* We don't care about the internal object, actually */
1779 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1781 m_natives.push_back(natives);
1784 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1792 sec.pIdentity = m_MyIdent;
1794 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1807 CPlugin *CPluginManager::GetPluginByOrder(int num)
1809 if (num < 1 || num > (int)GetPluginCount())
1817 IPluginIterator *iter = GetPluginIterator();
1818 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1820 pl = (CPlugin *)(iter->GetPlugin());
1826 const char *CPluginManager::GetStatusText(PluginStatus st)
1830 case Plugin_Running:
1836 case Plugin_Uncompiled:
1837 return "Uncompiled";
1838 case Plugin_BadLoad:
1848 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1852 const char *cmd = g_RootMenu.GetArgument(2);
1853 if (strcmp(cmd, "list") == 0)
1856 unsigned int id = 1;
1857 int plnum = GetPluginCount();
1861 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1864 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1867 IPluginIterator *iter = GetPluginIterator();
1868 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1870 IPlugin *pl = iter->GetPlugin();
1871 assert(pl->GetStatus() != Plugin_Created);
1873 const sm_plugininfo_t *info = pl->GetPublicInfo();
1874 if (pl->GetStatus() != Plugin_Running)
1876 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1878 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1880 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1881 if (IS_STR_FILLED(info->version))
1883 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1885 if (IS_STR_FILLED(info->author))
1887 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1889 g_RootMenu.ConsolePrint("%s", buffer);
1894 } else if (strcmp(cmd, "load") == 0) {
1897 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1903 const char *filename = g_RootMenu.GetArgument(3);
1905 char pluginfile[256];
1906 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1907 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1909 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1913 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1919 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1921 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
1925 } else if (strcmp(cmd, "unload") == 0) {
1928 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1933 int num = atoi(g_RootMenu.GetArgument(3));
1934 if (num < 1 || num > (int)GetPluginCount())
1936 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1940 IPluginIterator *iter = GetPluginIterator();
1941 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1943 IPlugin *pl = iter->GetPlugin();
1945 char name[PLATFORM_MAX_PATH];
1946 const sm_plugininfo_t *info = pl->GetPublicInfo();
1947 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1949 if (UnloadPlugin(pl))
1951 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1953 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1958 } else if (strcmp(cmd, "info") == 0) {
1961 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1965 int num = atoi(g_RootMenu.GetArgument(3));
1966 if (num < 1 || num > (int)GetPluginCount())
1968 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1972 CPlugin *pl = GetPluginByOrder(num);
1973 const sm_plugininfo_t *info = pl->GetPublicInfo();
1975 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1976 if (pl->GetStatus() <= Plugin_Error)
1978 if (IS_STR_FILLED(info->name))
1980 if (IS_STR_FILLED(info->description))
1982 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1984 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1987 if (IS_STR_FILLED(info->author))
1989 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1991 if (IS_STR_FILLED(info->version))
1993 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1995 if (IS_STR_FILLED(info->url))
1997 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1999 if (pl->GetStatus() == Plugin_Error)
2001 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2003 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
2004 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
2006 const char *typestr = "";
2007 switch (pl->GetType())
2009 case PluginType_MapUpdated:
2010 typestr = "Map Change if Updated";
2012 case PluginType_MapOnly:
2013 typestr = "Map Change";
2015 case PluginType_Private:
2016 case PluginType_Global:
2021 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2024 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2025 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2026 info->name ? info->name : "<none>",
2027 info->version ? info->version : "<none>");
2028 if (IS_STR_FILLED(info->url))
2030 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2035 } else if (strcmp(cmd, "debug") == 0) {
2038 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
2042 int num = atoi(g_RootMenu.GetArgument(3));
2043 if (num < 1 || num > (int)GetPluginCount())
2045 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
2050 const char *mode = g_RootMenu.GetArgument(4);
2051 if ((res=strcmp("on", mode)) && strcmp("off", mode))
2053 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
2065 CPlugin *pl = GetPluginByOrder(num);
2066 if (debug && pl->IsDebugging())
2068 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
2070 } else if (!debug && !pl->IsDebugging()) {
2071 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
2076 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
2078 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
2081 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
2082 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
2088 /* Draw the main menu */
2089 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2090 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2091 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2092 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2093 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2094 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
2097 void CPluginManager::ReloadOrUnloadPlugins()
2099 List<CPlugin *>::iterator iter;
2100 List<CPlugin *> tmp_list = m_plugins;
2104 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2107 if (pl->GetType() == PluginType_MapOnly)
2109 UnloadPlugin((IPlugin *)pl);
2110 } else if (pl->GetType() == PluginType_MapUpdated) {
2111 t = pl->GetFileTimeStamp();
2112 if (!t || t > pl->GetTimeStamp())
2114 pl->SetTimeStamp(t);
2115 UnloadPlugin((IPlugin *)pl);
2121 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2123 List<IPluginsListener *>::iterator iter;
2124 IPluginsListener *pListener;
2125 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2127 pListener = (*iter);
2128 pListener->OnPluginPauseChange(pl, paused);
2132 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
2134 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
2139 FakeNative *pNative = new FakeNative;
2141 pNative->func = g_pVM->CreateFakeNative(func, pNative);
2148 pNative->call = pFunction;
2149 pNative->name.assign(name);
2150 pNative->ctx = pFunction->GetParentContext();
2152 m_Natives.push_back(pNative);
2153 sm_trie_insert(m_pNativeLookup, name,pNative);
2155 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
2156 pPlugin->m_fakeNatives.push_back(pNative);
2161 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2163 List<CPlugin *>::iterator iter;
2165 IPluginFunction *pFunction;
2167 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2171 if (pPlugin->GetStatus() <= Plugin_Paused)
2173 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2177 pForward->AddFunction(pFunction);
2183 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2185 if (pToken->type != g_PluginIdent)
2190 return (CPlugin *)(pToken->ptr);
2193 void CPluginManager::ExecAndGenPluginConfs()
2195 List<CPlugin *>::iterator iter;