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++)
96 List<WeakNative *>::iterator iter;
97 for (iter=m_WeakNatives.begin(); iter!=m_WeakNatives.end(); iter++)
101 m_WeakNatives.clear();
104 void CPlugin::InitIdentity()
108 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
109 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
110 m_ctx.base->SetIdentity(m_ident);
114 Handle_t CPlugin::GetMyHandle()
119 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
121 char fullpath[PLATFORM_MAX_PATH];
122 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
123 FILE *fp = fopen(fullpath, "rb");
125 CPlugin *pPlugin = new CPlugin(file);
131 snprintf(error, maxlength, "Unable to open file");
133 pPlugin->m_status = Plugin_BadLoad;
138 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
144 snprintf(error, maxlength, "Error %d while parsing plugin", err);
146 pPlugin->m_status = Plugin_BadLoad;
152 pPlugin->m_plugin = pl;
157 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
159 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
161 if (exists && remove)
163 sm_trie_delete(m_pProps, prop);
169 bool CPlugin::SetProperty(const char *prop, void *ptr)
171 return sm_trie_insert(m_pProps, prop, ptr);
174 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
181 /* :NOTICE: We will eventually need to change these natives
182 * for swapping in new contexts
184 if (m_ctx.co || m_ctx.ctx)
189 m_status = Plugin_Uncompiled;
192 m_ctx.co = vm->StartCompilation(m_plugin);
197 void CPlugin::CancelMyCompile()
204 m_ctx.vm->AbortCompilation(m_ctx.co);
209 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
217 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
220 memset(&m_ctx, 0, sizeof(m_ctx));
223 snprintf(error, maxlength, "JIT failed to compile (error %d)", err);
228 m_ctx.base = new BaseContext(m_ctx.ctx);
229 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
231 m_status = Plugin_Created;
239 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
241 PluginStatus old_status = m_status;
244 if (old_status == Plugin_Running)
246 /* Tell everyone we're now paused */
247 g_PluginSys._SetPauseState(this, true);
251 va_start(ap, error_fmt);
252 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
257 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
261 void CPlugin::UpdateInfo()
263 /* Now grab the info */
265 IPluginContext *base = GetBaseContext();
266 int err = base->FindPubvarByName("myinfo", &idx);
268 memset(&m_info, 0, sizeof(m_info));
270 if (err == SP_ERROR_NONE)
272 struct sm_plugininfo_c_t
280 sm_plugininfo_c_t *cinfo;
283 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
284 base->LocalToString(cinfo->name, (char **)&m_info.name);
285 base->LocalToString(cinfo->description, (char **)&m_info.description);
286 base->LocalToString(cinfo->author, (char **)&m_info.author);
287 base->LocalToString(cinfo->url, (char **)&m_info.url);
288 base->LocalToString(cinfo->version, (char **)&m_info.version);
291 m_info.author = m_info.author ? m_info.author : "";
292 m_info.description = m_info.description ? m_info.description : "";
293 m_info.name = m_info.name ? m_info.name : "";
294 m_info.url = m_info.url ? m_info.url : "";
295 m_info.version = m_info.version ? m_info.version : "";
298 void CPlugin::Call_OnPluginStart()
300 if (m_status != Plugin_Loaded)
305 m_status = Plugin_Running;
308 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
315 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
317 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
321 if ((pFunction = m_ctx.base->GetFunctionByName("OnMapStart")) != NULL)
323 pFunction->Execute(NULL);
326 if (SM_AreConfigsExecuted())
328 SM_ExecuteForPlugin(GetBaseContext());
333 void CPlugin::Call_OnPluginEnd()
335 if (m_status > Plugin_Paused)
341 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
347 pFunction->Execute(&result);
350 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
352 if (m_status != Plugin_Created)
357 m_status = Plugin_Loaded;
361 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
368 pFunction->PushCell(m_handle);
369 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
370 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
371 pFunction->PushCell(maxlength);
372 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
377 if (!result || m_status != Plugin_Loaded)
385 const sp_plugin_t *CPlugin::GetPluginStructure()
390 IPluginContext *CPlugin::GetBaseContext()
395 sp_context_t *CPlugin::GetContext()
400 const char *CPlugin::GetFilename()
405 PluginType CPlugin::GetType()
410 const sm_plugininfo_t *CPlugin::GetPublicInfo()
415 unsigned int CPlugin::GetSerial()
420 PluginStatus CPlugin::GetStatus()
425 bool CPlugin::IsDebugging()
432 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
435 bool CPlugin::SetPauseState(bool paused)
437 if (paused && GetStatus() != Plugin_Paused)
440 } else if (!paused && GetStatus() != Plugin_Running) {
444 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
448 pFunction->PushCell(paused ? 1 : 0);
449 pFunction->Execute(&result);
454 m_status = Plugin_Paused;
455 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
457 m_status = Plugin_Running;
458 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
461 g_PluginSys._SetPauseState(this, paused);
466 IdentityToken_t *CPlugin::GetIdentity()
471 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
479 snprintf(error, maxlength, "Plugin is not runnable.");
484 if (debug && IsDebugging())
488 snprintf(error, maxlength, "Plugin is already in debug mode.");
491 } else if (!debug && !IsDebugging()) {
494 snprintf(error, maxlength, "Plugins is already in production mode.");
499 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
500 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
504 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
509 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
513 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
514 new_ctx->hp = m_ctx.ctx->hp;
515 new_ctx->sp = m_ctx.ctx->sp;
516 new_ctx->frm = m_ctx.ctx->frm;
517 new_ctx->dbreak = m_ctx.ctx->dbreak;
518 new_ctx->context = m_ctx.ctx->context;
519 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
521 uint32_t nativeCount = m_plugin->info.natives_num;
522 for (uint32_t i=0; i<nativeCount; i++)
524 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
525 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
528 g_pVM->FreeContext(m_ctx.ctx);
530 m_ctx.base->SetContext(new_ctx);
536 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
544 bool CPlugin::IsRunnable()
546 return (m_status <= Plugin_Paused) ? true : false;
549 time_t CPlugin::GetFileTimeStamp()
551 char path[PLATFORM_MAX_PATH];
552 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
553 #ifdef PLATFORM_WINDOWS
555 if (_stat(path, &s) != 0)
556 #elif defined PLATFORM_POSIX
558 if (stat(path, &s) != 0)
567 time_t CPlugin::GetTimeStamp()
572 void CPlugin::SetTimeStamp(time_t t)
577 void CPlugin::AddLangFile(unsigned int index)
579 m_PhraseFiles.push_back(index);
582 size_t CPlugin::GetLangFileCount()
584 return m_PhraseFiles.size();
587 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
589 return m_PhraseFiles.at(index);
592 void CPlugin::DependencyDropped(CPlugin *pOwner)
599 List<String>::iterator reqlib_iter;
600 List<String>::iterator lib_iter;
601 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
603 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
605 if ((*reqlib_iter) == (*lib_iter))
607 m_LibraryMissing = true;
612 List<FakeNative *>::iterator iter;
616 unsigned int unbound = 0;
618 for (iter = pOwner->m_fakeNatives.begin();
619 iter != pOwner->m_fakeNatives.end();
623 /* Find this native! */
624 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
629 m_ctx.base->GetNativeByIndex(idx, &native);
631 native->status = SP_NATIVE_UNBOUND;
637 m_FakeNativesMissing = true;
640 /* :IDEA: in the future, add native trapping? */
641 if (m_FakeNativesMissing || m_LibraryMissing)
643 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
646 m_dependsOn.remove(pOwner);
649 unsigned int CPlugin::GetConfigCount()
651 return (unsigned int)m_configs.size();
654 AutoConfig *CPlugin::GetConfig(unsigned int i)
656 if (i >= GetConfigCount())
664 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
666 AutoConfig *c = new AutoConfig;
670 c->create = autoCreate;
672 m_configs.push_back(c);
679 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
685 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
690 bool CPluginManager::CPluginIterator::MorePlugins()
692 return (current != mylist->end());
695 void CPluginManager::CPluginIterator::NextPlugin()
700 void CPluginManager::CPluginIterator::Release()
702 g_PluginSys.ReleaseIterator(this);
705 CPluginManager::CPluginIterator::~CPluginIterator()
709 void CPluginManager::CPluginIterator::Reset()
711 current = mylist->begin();
718 CPluginManager::CPluginManager()
720 m_LoadLookup = sm_trie_create();
721 m_AllPluginsLoaded = false;
723 m_pNativeLookup = sm_trie_create();
726 CPluginManager::~CPluginManager()
729 * Ignore the fact that there might be plugins in the cache.
730 * This usually means that Core is not being unloaded properly, and everything
731 * will crash anyway. YAY
733 sm_trie_destroy(m_LoadLookup);
734 sm_trie_destroy(m_pNativeLookup);
736 CStack<CPluginManager::CPluginIterator *>::iterator iter;
737 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
744 void CPluginManager::Shutdown()
746 List<CPlugin *>::iterator iter;
748 while ((iter = m_plugins.begin()) != m_plugins.end())
754 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
756 /* First read in the database of plugin settings */
758 unsigned int line, col;
759 m_AllPluginsLoaded = false;
760 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
762 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
763 const char *err_msg = g_TextParser.GetSMCErrorString(err);
766 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
770 LoadPluginsFromDir(basedir, NULL);
773 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
775 char base_path[PLATFORM_MAX_PATH];
777 /* Form the current path to start reading from */
778 if (localpath == NULL)
780 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
782 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
785 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
790 g_LibSys.GetPlatformError(error, sizeof(error));
791 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
792 g_Logger.LogError("[SM] Platform returned error: %s", error);
796 while (dir->MoreFiles())
798 if (dir->IsEntryDirectory()
799 && (strcmp(dir->GetEntryName(), ".") != 0)
800 && (strcmp(dir->GetEntryName(), "..") != 0)
801 && (strcmp(dir->GetEntryName(), "disabled") != 0)
802 && (strcmp(dir->GetEntryName(), "optional") != 0))
804 char new_local[PLATFORM_MAX_PATH];
805 if (localpath == NULL)
807 /* If no path yet, don't add a former slash */
808 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
810 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
812 LoadPluginsFromDir(basedir, new_local);
813 } else if (dir->IsEntryFile()) {
814 const char *name = dir->GetEntryName();
815 size_t len = strlen(name);
817 && strcmp(&name[len-4], ".smx") == 0)
819 /* If the filename matches, load the plugin */
820 char plugin[PLATFORM_MAX_PATH];
821 if (localpath == NULL)
823 snprintf(plugin, sizeof(plugin), "%s", name);
825 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
827 LoadAutoPlugin(plugin);
832 g_LibSys.CloseDirectory(dir);
835 //well i have discovered that gabe newell is very fat, so i wrote this comment now
836 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
839 * Does this plugin already exist?
842 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
844 /* Check to see if we should try reloading it */
845 if (pPlugin->GetStatus() == Plugin_BadLoad
846 || pPlugin->GetStatus() == Plugin_Error
847 || pPlugin->GetStatus() == Plugin_Failed)
849 UnloadPlugin(pPlugin);
855 return LoadRes_AlreadyLoaded;
859 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
861 assert(pPlugin != NULL);
863 pPlugin->m_type = PluginType_MapUpdated;
865 ICompilation *co = NULL;
867 if (pPlugin->m_status == Plugin_Uncompiled)
869 co = pPlugin->StartMyCompile(g_pVM);
872 PluginSettings *pset;
873 unsigned int setcount = m_PluginInfo.GetSettingsNum();
874 for (unsigned int i=0; i<setcount; i++)
876 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
880 pPlugin->m_type = pset->type_val;
883 for (unsigned int j=0; j<pset->opts_num; j++)
885 const char *key, *val;
886 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
891 if (!g_pVM->SetCompilationOption(co, key, val))
895 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
897 pPlugin->CancelMyCompile();
905 /* Do the actual compiling */
908 pPlugin->FinishMyCompile(error, maxlength);
913 if (pPlugin->GetStatus() == Plugin_Created)
915 AddCoreNativesToPlugin(pPlugin);
916 pPlugin->InitIdentity();
917 if (pPlugin->Call_AskPluginLoad(error, maxlength))
919 /* Autoload any modules */
920 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
924 /* Save the time stamp */
925 time_t t = pPlugin->GetFileTimeStamp();
926 pPlugin->SetTimeStamp(t);
933 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
936 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
942 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
948 if (res == LoadRes_AlreadyLoaded)
956 /* Run second pass if we need to */
957 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
959 if (!RunSecondPass(pl, error, maxlength))
969 void CPluginManager::LoadAutoPlugin(const char *plugin)
973 char error[255] = "Unknown error";
975 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
977 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
978 pl->SetErrorState(Plugin_Failed, "%s", error);
981 if (res == LoadRes_Successful)
987 void CPluginManager::AddPlugin(CPlugin *pPlugin)
989 List<IPluginsListener *>::iterator iter;
990 IPluginsListener *pListener;
992 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
995 pListener->OnPluginCreated(pPlugin);
998 m_plugins.push_back(pPlugin);
999 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1002 void CPluginManager::LoadAll_SecondPass()
1004 List<CPlugin *>::iterator iter;
1008 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1011 if (pPlugin->GetStatus() == Plugin_Loaded)
1014 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1016 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1017 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1022 m_AllPluginsLoaded = true;
1025 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1034 IPluginContext *pBase = pPlugin->GetBaseContext();
1035 uint32_t num = pBase->GetPubVarsNum();
1036 sp_pubvar_t *pubvar;
1038 char pathfile[PLATFORM_MAX_PATH];
1040 for (uint32_t i=0; i<num; i++)
1042 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1046 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1048 pl = (_pl *)pubvar->offs;
1049 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1053 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1057 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1058 if (strcmp(pathfile, file) == 0)
1062 if (pl->required == false)
1064 IPluginFunction *pFunc;
1066 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[6]);
1067 if ((pFunc=pBase->GetFunctionByName(buffer)))
1070 pFunc->Execute(&res);
1071 if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
1075 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1081 /* Check that we aren't registering the same library twice */
1082 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1084 pPlugin->m_RequiredLibs.push_back(name);
1088 List<CPlugin *>::iterator iter;
1091 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1094 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1104 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1115 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1117 /* Find any extensions this plugin needs */
1126 IPluginContext *pBase = pPlugin->GetBaseContext();
1127 uint32_t num = pBase->GetPubVarsNum();
1128 sp_pubvar_t *pubvar;
1130 char path[PLATFORM_MAX_PATH];
1132 for (uint32_t i=0; i<num; i++)
1134 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1138 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1140 ext = (_ext *)pubvar->offs;
1141 if (!ext->required && !ext->autoload)
1145 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1149 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1155 /* Attempt to auto-load if necessary */
1158 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1159 g_Extensions.LoadAutoExtension(path);
1161 } else if (pass == 2) {
1162 /* Is this required? */
1165 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1166 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1168 pExt = g_Extensions.FindExtensionByName(name);
1170 /* :TODO: should we bind to unloaded extensions?
1171 * Currently the extension manager will ignore this.
1173 if (!pExt || !pExt->IsRunning(NULL, 0))
1177 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1181 g_Extensions.BindChildPlugin(pExt, pPlugin);
1191 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1193 /* Second pass for extension requirements */
1194 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1199 /* Bind all extra natives */
1200 g_Extensions.BindAllNativesToPlugin(pPlugin);
1201 AddFakeNativesToPlugin(pPlugin);
1203 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1208 /* Find any unbound natives
1209 * Right now, these are not allowed
1211 IPluginContext *pContext = pPlugin->GetBaseContext();
1212 uint32_t num = pContext->GetNativesNum();
1213 sp_native_t *native;
1214 for (unsigned int i=0; i<num; i++)
1216 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1220 if (native->status == SP_NATIVE_UNBOUND
1221 && native->name[0] != '@'
1222 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1226 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1232 /* Finish by telling all listeners */
1233 List<IPluginsListener *>::iterator iter;
1234 IPluginsListener *pListener;
1235 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1237 pListener = (*iter);
1238 pListener->OnPluginLoaded(pPlugin);
1241 /* Tell this plugin to finish initializing itself */
1242 pPlugin->Call_OnPluginStart();
1244 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1245 if (pPlugin->GetStatus() >= Plugin_Paused && pPlugin->m_fakeNatives.size())
1247 List<CPlugin *>::iterator pl_iter;
1249 for (pl_iter = m_plugins.begin();
1250 pl_iter != m_plugins.end();
1253 pOther = (*pl_iter);
1254 if (pOther->GetStatus() == Plugin_Error
1255 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1257 TryRefreshDependencies(pOther);
1265 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1267 List<sp_nativeinfo_t *>::iterator iter;
1269 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1271 sp_nativeinfo_t *natives = (*iter);
1272 IPluginContext *ctx = pPlugin->GetBaseContext();
1274 /* Attempt to bind every native! */
1275 while (natives[i].func != NULL)
1277 ctx->BindNative(&natives[i++]);
1282 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1284 assert(pPlugin->GetBaseContext() != NULL);
1286 AddFakeNativesToPlugin(pPlugin);
1288 List<String>::iterator lib_iter;
1289 List<String>::iterator req_iter;
1290 List<CPlugin *>::iterator pl_iter;
1292 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1295 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1298 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1300 if ((*req_iter) == (*lib_iter))
1308 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1313 /* Find any unbound natives
1314 * Right now, these are not allowed
1316 IPluginContext *pContext = pPlugin->GetBaseContext();
1317 uint32_t num = pContext->GetNativesNum();
1318 sp_native_t *native;
1319 for (unsigned int i=0; i<num; i++)
1321 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1325 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1327 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1332 /* If we got here, all natives are okay again! */
1333 pPlugin->m_status = Plugin_Running;
1334 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1336 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1337 _SetPauseState(pPlugin, false);
1341 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1343 IPluginContext *pContext = pPlugin->GetBaseContext();
1344 sp_nativeinfo_t native;
1346 List<FakeNative *>::iterator iter;
1347 FakeNative *pNative;
1349 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1352 ctx = pNative->ctx->GetContext();
1353 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1355 /* Ignore natives in paused plugins */
1358 native.name = pNative->name.c_str();
1359 native.func = pNative->func;
1360 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1363 pContext->FindNativeByName(native.name, &idx);
1364 if (pPlugin->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL)
1366 WeakNative *wkn = new WeakNative(pPlugin, idx);
1367 GetPluginByCtx(ctx)->m_WeakNatives.push_back(wkn);
1370 /* Add us as a dependency, but we're careful not to do this circularly! */
1371 if (pNative->ctx != pContext)
1373 CPlugin *pOther = GetPluginByCtx(ctx);
1374 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1376 pOther->m_dependents.push_back(pPlugin);
1378 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1380 pPlugin->m_dependsOn.push_back(pOther);
1387 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1389 CPlugin *pPlugin = (CPlugin *)plugin;
1391 /* This prevents removal during insertion or anything else weird */
1392 if (m_plugins.find(pPlugin) == m_plugins.end())
1397 /* Remove us from the lookup table and linked list */
1398 m_plugins.remove(pPlugin);
1399 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1401 /* Go through all dependent plugins and tell them this plugin is now gone */
1402 List<CPlugin *>::iterator pl_iter;
1404 for (pl_iter = pPlugin->m_dependents.begin();
1405 pl_iter != pPlugin->m_dependents.end();
1408 pOther = (*pl_iter);
1409 pOther->DependencyDropped(pPlugin);
1412 /* Tell everyone we depend on that we no longer exist */
1413 for (pl_iter = pPlugin->m_dependsOn.begin();
1414 pl_iter != pPlugin->m_dependsOn.end();
1417 pOther = (*pl_iter);
1418 pOther->m_dependents.remove(pPlugin);
1421 List<IPluginsListener *>::iterator iter;
1422 IPluginsListener *pListener;
1424 if (pPlugin->GetStatus() <= Plugin_Error)
1426 /* Notify listeners of unloading */
1427 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1429 pListener = (*iter);
1430 pListener->OnPluginUnloaded(pPlugin);
1433 pPlugin->Call_OnPluginEnd();
1436 /* Remove all of our native functions */
1437 List<FakeNative *>::iterator fn_iter;
1438 FakeNative *pNative;
1439 for (fn_iter = pPlugin->m_fakeNatives.begin();
1440 fn_iter != pPlugin->m_fakeNatives.end();
1443 pNative = (*fn_iter);
1444 m_Natives.remove(pNative);
1445 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1446 g_pVM->DestroyFakeNative(pNative->func);
1450 /* 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++)
1456 sp_context_t *ctx = wkn->pl->GetContext();
1457 ctx->natives[wkn->idx].status = SP_NATIVE_UNBOUND;
1460 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1462 /* Notify listeners of destruction */
1463 pListener = (*iter);
1464 pListener->OnPluginDestroyed(pPlugin);
1467 /* Tell the plugin to delete itself */
1473 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1475 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1479 unsigned int CPluginManager::GetPluginCount()
1481 return m_plugins.size();
1484 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1486 m_listeners.push_back(listener);
1489 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1491 m_listeners.remove(listener);
1494 IPluginIterator *CPluginManager::GetPluginIterator()
1496 if (m_iters.empty())
1498 return new CPluginIterator(&m_plugins);
1500 CPluginIterator *iter = m_iters.front();
1507 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1512 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1514 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1515 size_t alias_len = 0;
1516 size_t local_len = 0;
1518 const char *ptr = alias;
1519 unsigned int alias_explicit_paths = 0;
1520 unsigned int alias_path_end = 0;
1521 while (*ptr != '\0')
1523 if (*ptr == '\\' || *ptr == '/')
1525 alias_explicit_paths++;
1526 alias_path_end = alias_len;
1532 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1534 /* Trailing slash is totally invalid here */
1539 unsigned int local_explicit_paths = 0;
1540 unsigned int local_path_end = 0;
1541 while (*ptr != '\0')
1543 if (*ptr == '\\' || *ptr == '/')
1545 local_explicit_paths++;
1546 local_path_end = local_len;
1552 /* If the alias has more explicit paths than the real path,
1553 * no match will be possible.
1555 if (alias_explicit_paths > local_explicit_paths)
1560 if (alias_explicit_paths)
1562 /* We need to find if the paths match now. For example, these should all match:
1564 * csdm optional/csdm
1565 * csdm/ban optional/crab/csdm/ban
1567 const char *aliasptr = alias;
1568 const char *localptr = localpath;
1572 if (*aliasptr != *localptr)
1574 /* We have to knock one path off */
1575 local_explicit_paths--;
1576 if (alias_explicit_paths > local_explicit_paths)
1578 /* Skip out if we're gonna have an impossible match */
1581 /* Eat up localptr tokens until we get a result */
1582 while (((localptr - localpath) < (int)local_path_end)
1584 && *localptr != '\\')
1588 /* Check if we hit the end of our searchable area.
1589 * This probably isn't possible because of the path
1590 * count check, but it's a good idea anyway.
1592 if ((localptr - localpath) >= (int)local_path_end)
1596 /* Consume the slash token */
1599 /* Reset the alias pointer so we can continue consuming */
1605 * This is safe because if localptr terminates early, aliasptr will too
1609 /* We should never reach the end of the string because of this check. */
1610 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1611 bool localend = (localptr - localpath) > (int)local_path_end;
1612 if (aliasend || localend)
1614 if (aliasend && localend)
1616 /* we matched, and we can break out now */
1620 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1625 /* If we got here, it's safe to compare the next two tokens */
1626 if (*localptr != *aliasptr)
1637 /* If we got here, it's time to compare filenames */
1638 const char *aliasptr = alias;
1639 const char *localptr = localpath;
1641 if (alias_explicit_paths)
1643 aliasptr = &alias[alias_path_end + 1];
1646 if (local_explicit_paths)
1648 localptr = &localpath[local_path_end + 1];
1653 if (*aliasptr == '*')
1655 /* First, see if this is the last character */
1656 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1658 /* If so, there's no need to match anything else */
1661 /* Otherwise, we need to search for an appropriate matching sequence in local.
1662 * Note that we only need to search up to the next asterisk.
1666 const char *local_orig = localptr;
1670 while (*aliasptr != '\0' && *aliasptr != '*')
1672 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1673 if (*aliasptr != *localptr)
1683 /* If we didn't get a match, we need to advance the search stream.
1684 * This will let us skip tokens while still searching for another match.
1686 localptr = ++local_orig;
1687 /* Make sure we don't go out of bounds */
1688 if (*localptr == '\0')
1699 /* If we got a match, move on to the next token */
1702 } else if (*aliasptr == '\0') {
1703 if (*localptr == '\0'
1705 strcmp(localptr, ".smx") == 0)
1711 } else if (*aliasptr != *localptr) {
1721 bool CPluginManager::IsLateLoadTime() const
1723 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1726 void CPluginManager::OnSourceModAllInitialized()
1728 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1731 g_HandleSys.InitAccessDefaults(NULL, &sec);
1733 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1734 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1736 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1737 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1739 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1741 g_ShareSys.AddInterface(NULL, this);
1744 void CPluginManager::OnSourceModShutdown()
1746 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1748 List<CPlugin *>::iterator iter;
1749 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1751 UnloadPlugin((*iter));
1754 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1755 g_ShareSys.DestroyIdentType(g_PluginIdent);
1756 g_ShareSys.DestroyIdentity(m_MyIdent);
1759 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1761 /* We don't care about the internal object, actually */
1764 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1766 m_natives.push_back(natives);
1769 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1777 sec.pIdentity = m_MyIdent;
1779 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1792 CPlugin *CPluginManager::GetPluginByOrder(int num)
1794 if (num < 1 || num > (int)GetPluginCount())
1802 IPluginIterator *iter = GetPluginIterator();
1803 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1805 pl = (CPlugin *)(iter->GetPlugin());
1811 const char *CPluginManager::GetStatusText(PluginStatus st)
1815 case Plugin_Running:
1821 case Plugin_Uncompiled:
1822 return "Uncompiled";
1823 case Plugin_BadLoad:
1833 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1837 const char *cmd = g_RootMenu.GetArgument(2);
1838 if (strcmp(cmd, "list") == 0)
1841 unsigned int id = 1;
1842 int plnum = GetPluginCount();
1846 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1849 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1852 IPluginIterator *iter = GetPluginIterator();
1853 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1855 IPlugin *pl = iter->GetPlugin();
1856 assert(pl->GetStatus() != Plugin_Created);
1858 const sm_plugininfo_t *info = pl->GetPublicInfo();
1859 if (pl->GetStatus() != Plugin_Running)
1861 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1863 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1865 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1866 if (IS_STR_FILLED(info->version))
1868 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1870 if (IS_STR_FILLED(info->author))
1872 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1874 g_RootMenu.ConsolePrint("%s", buffer);
1879 } else if (strcmp(cmd, "load") == 0) {
1882 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1888 const char *filename = g_RootMenu.GetArgument(3);
1890 char pluginfile[256];
1891 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1892 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1894 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1898 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1904 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1906 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
1910 } else if (strcmp(cmd, "unload") == 0) {
1913 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1918 int num = atoi(g_RootMenu.GetArgument(3));
1919 if (num < 1 || num > (int)GetPluginCount())
1921 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1925 IPluginIterator *iter = GetPluginIterator();
1926 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1928 IPlugin *pl = iter->GetPlugin();
1930 char name[PLATFORM_MAX_PATH];
1931 const sm_plugininfo_t *info = pl->GetPublicInfo();
1932 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1934 if (UnloadPlugin(pl))
1936 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1938 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1943 } else if (strcmp(cmd, "info") == 0) {
1946 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1950 int num = atoi(g_RootMenu.GetArgument(3));
1951 if (num < 1 || num > (int)GetPluginCount())
1953 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1957 CPlugin *pl = GetPluginByOrder(num);
1958 const sm_plugininfo_t *info = pl->GetPublicInfo();
1960 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1961 if (pl->GetStatus() <= Plugin_Error)
1963 if (IS_STR_FILLED(info->name))
1965 if (IS_STR_FILLED(info->description))
1967 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
1969 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1972 if (IS_STR_FILLED(info->author))
1974 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1976 if (IS_STR_FILLED(info->version))
1978 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1980 if (IS_STR_FILLED(info->url))
1982 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1984 if (pl->GetStatus() == Plugin_Error)
1986 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
1988 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
1989 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
1991 const char *typestr = "";
1992 switch (pl->GetType())
1994 case PluginType_MapUpdated:
1995 typestr = "Map Change if Updated";
1997 case PluginType_MapOnly:
1998 typestr = "Map Change";
2000 case PluginType_Private:
2001 case PluginType_Global:
2006 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2009 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2010 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2011 info->name ? info->name : "<none>",
2012 info->version ? info->version : "<none>");
2013 if (IS_STR_FILLED(info->url))
2015 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2020 } else if (strcmp(cmd, "debug") == 0) {
2023 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
2027 int num = atoi(g_RootMenu.GetArgument(3));
2028 if (num < 1 || num > (int)GetPluginCount())
2030 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
2035 const char *mode = g_RootMenu.GetArgument(4);
2036 if ((res=strcmp("on", mode)) && strcmp("off", mode))
2038 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
2050 CPlugin *pl = GetPluginByOrder(num);
2051 if (debug && pl->IsDebugging())
2053 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
2055 } else if (!debug && !pl->IsDebugging()) {
2056 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
2061 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
2063 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
2066 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
2067 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
2073 /* Draw the main menu */
2074 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2075 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2076 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2077 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2078 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2079 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
2082 void CPluginManager::ReloadOrUnloadPlugins()
2084 List<CPlugin *>::iterator iter;
2085 List<CPlugin *> tmp_list = m_plugins;
2089 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2092 if (pl->GetType() == PluginType_MapOnly)
2094 UnloadPlugin((IPlugin *)pl);
2095 } else if (pl->GetType() == PluginType_MapUpdated) {
2096 t = pl->GetFileTimeStamp();
2097 if (!t || t > pl->GetTimeStamp())
2099 pl->SetTimeStamp(t);
2100 UnloadPlugin((IPlugin *)pl);
2106 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2108 List<IPluginsListener *>::iterator iter;
2109 IPluginsListener *pListener;
2110 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2112 pListener = (*iter);
2113 pListener->OnPluginPauseChange(pl, paused);
2117 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
2119 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
2124 FakeNative *pNative = new FakeNative;
2126 pNative->func = g_pVM->CreateFakeNative(func, pNative);
2133 pNative->call = pFunction;
2134 pNative->name.assign(name);
2135 pNative->ctx = pFunction->GetParentContext();
2137 m_Natives.push_back(pNative);
2138 sm_trie_insert(m_pNativeLookup, name,pNative);
2140 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
2141 pPlugin->m_fakeNatives.push_back(pNative);
2146 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2148 List<CPlugin *>::iterator iter;
2150 IPluginFunction *pFunction;
2152 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2156 if (pPlugin->GetStatus() <= Plugin_Paused)
2158 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2162 pForward->AddFunction(pFunction);
2168 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2170 if (pToken->type != g_PluginIdent)
2175 return (CPlugin *)(pToken->ptr);
2178 void CPluginManager::ExecAndGenPluginConfs()
2180 List<CPlugin *>::iterator iter;