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 void CPlugin::LibraryActions(bool dropping)
430 List<String>::iterator iter;
431 for (iter = m_Libraries.begin();
432 iter != m_Libraries.end();
435 g_PluginSys.OnLibraryAction((*iter).c_str(), dropping);
439 bool CPlugin::SetPauseState(bool paused)
441 if (paused && GetStatus() != Plugin_Running)
444 } else if (!paused && GetStatus() != Plugin_Paused) {
450 LibraryActions(true);
453 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
457 pFunction->PushCell(paused ? 1 : 0);
458 pFunction->Execute(&result);
463 m_status = Plugin_Paused;
464 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
466 m_status = Plugin_Running;
467 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
470 g_PluginSys._SetPauseState(this, paused);
474 LibraryActions(false);
480 IdentityToken_t *CPlugin::GetIdentity()
485 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
493 snprintf(error, maxlength, "Plugin is not runnable.");
498 if (debug && IsDebugging())
502 snprintf(error, maxlength, "Plugin is already in debug mode.");
505 } else if (!debug && !IsDebugging()) {
508 snprintf(error, maxlength, "Plugins is already in production mode.");
513 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
514 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
518 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
523 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
527 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
528 new_ctx->hp = m_ctx.ctx->hp;
529 new_ctx->sp = m_ctx.ctx->sp;
530 new_ctx->frm = m_ctx.ctx->frm;
531 new_ctx->dbreak = m_ctx.ctx->dbreak;
532 new_ctx->context = m_ctx.ctx->context;
533 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
535 uint32_t nativeCount = m_plugin->info.natives_num;
536 for (uint32_t i=0; i<nativeCount; i++)
538 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
539 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
542 g_pVM->FreeContext(m_ctx.ctx);
544 m_ctx.base->SetContext(new_ctx);
550 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
558 bool CPlugin::IsRunnable()
560 return (m_status <= Plugin_Paused) ? true : false;
563 time_t CPlugin::GetFileTimeStamp()
565 char path[PLATFORM_MAX_PATH];
566 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
567 #ifdef PLATFORM_WINDOWS
569 if (_stat(path, &s) != 0)
570 #elif defined PLATFORM_POSIX
572 if (stat(path, &s) != 0)
581 time_t CPlugin::GetTimeStamp()
586 void CPlugin::SetTimeStamp(time_t t)
591 void CPlugin::AddLangFile(unsigned int index)
593 m_PhraseFiles.push_back(index);
596 size_t CPlugin::GetLangFileCount()
598 return m_PhraseFiles.size();
601 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
603 return m_PhraseFiles.at(index);
606 void CPlugin::DependencyDropped(CPlugin *pOwner)
613 List<String>::iterator reqlib_iter;
614 List<String>::iterator lib_iter;
615 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
617 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
619 if ((*reqlib_iter) == (*lib_iter))
621 m_LibraryMissing = true;
626 List<FakeNative *>::iterator iter;
630 unsigned int unbound = 0;
632 for (iter = pOwner->m_fakeNatives.begin();
633 iter != pOwner->m_fakeNatives.end();
637 /* Find this native! */
638 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
643 m_ctx.base->GetNativeByIndex(idx, &native);
645 native->status = SP_NATIVE_UNBOUND;
651 m_FakeNativesMissing = true;
654 /* :IDEA: in the future, add native trapping? */
655 if (m_FakeNativesMissing || m_LibraryMissing)
657 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
660 m_dependsOn.remove(pOwner);
663 unsigned int CPlugin::GetConfigCount()
665 return (unsigned int)m_configs.size();
668 AutoConfig *CPlugin::GetConfig(unsigned int i)
670 if (i >= GetConfigCount())
678 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
680 AutoConfig *c = new AutoConfig;
684 c->create = autoCreate;
686 m_configs.push_back(c);
693 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
699 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
704 bool CPluginManager::CPluginIterator::MorePlugins()
706 return (current != mylist->end());
709 void CPluginManager::CPluginIterator::NextPlugin()
714 void CPluginManager::CPluginIterator::Release()
716 g_PluginSys.ReleaseIterator(this);
719 CPluginManager::CPluginIterator::~CPluginIterator()
723 void CPluginManager::CPluginIterator::Reset()
725 current = mylist->begin();
732 CPluginManager::CPluginManager()
734 m_LoadLookup = sm_trie_create();
735 m_AllPluginsLoaded = false;
737 m_pNativeLookup = sm_trie_create();
740 CPluginManager::~CPluginManager()
743 * Ignore the fact that there might be plugins in the cache.
744 * This usually means that Core is not being unloaded properly, and everything
745 * will crash anyway. YAY
747 sm_trie_destroy(m_LoadLookup);
748 sm_trie_destroy(m_pNativeLookup);
750 CStack<CPluginManager::CPluginIterator *>::iterator iter;
751 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
758 void CPluginManager::Shutdown()
760 List<CPlugin *>::iterator iter;
762 while ((iter = m_plugins.begin()) != m_plugins.end())
768 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
770 /* First read in the database of plugin settings */
772 unsigned int line, col;
773 m_AllPluginsLoaded = false;
774 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
776 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
777 const char *err_msg = g_TextParser.GetSMCErrorString(err);
780 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
784 LoadPluginsFromDir(basedir, NULL);
787 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
789 char base_path[PLATFORM_MAX_PATH];
791 /* Form the current path to start reading from */
792 if (localpath == NULL)
794 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
796 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
799 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
804 g_LibSys.GetPlatformError(error, sizeof(error));
805 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
806 g_Logger.LogError("[SM] Platform returned error: %s", error);
810 while (dir->MoreFiles())
812 if (dir->IsEntryDirectory()
813 && (strcmp(dir->GetEntryName(), ".") != 0)
814 && (strcmp(dir->GetEntryName(), "..") != 0)
815 && (strcmp(dir->GetEntryName(), "disabled") != 0)
816 && (strcmp(dir->GetEntryName(), "optional") != 0))
818 char new_local[PLATFORM_MAX_PATH];
819 if (localpath == NULL)
821 /* If no path yet, don't add a former slash */
822 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
824 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
826 LoadPluginsFromDir(basedir, new_local);
827 } else if (dir->IsEntryFile()) {
828 const char *name = dir->GetEntryName();
829 size_t len = strlen(name);
831 && strcmp(&name[len-4], ".smx") == 0)
833 /* If the filename matches, load the plugin */
834 char plugin[PLATFORM_MAX_PATH];
835 if (localpath == NULL)
837 snprintf(plugin, sizeof(plugin), "%s", name);
839 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
841 LoadAutoPlugin(plugin);
846 g_LibSys.CloseDirectory(dir);
849 //well i have discovered that gabe newell is very fat, so i wrote this comment now
850 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
853 * Does this plugin already exist?
856 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
858 /* Check to see if we should try reloading it */
859 if (pPlugin->GetStatus() == Plugin_BadLoad
860 || pPlugin->GetStatus() == Plugin_Error
861 || pPlugin->GetStatus() == Plugin_Failed)
863 UnloadPlugin(pPlugin);
869 return LoadRes_AlreadyLoaded;
873 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
875 assert(pPlugin != NULL);
877 pPlugin->m_type = PluginType_MapUpdated;
879 ICompilation *co = NULL;
881 if (pPlugin->m_status == Plugin_Uncompiled)
883 co = pPlugin->StartMyCompile(g_pVM);
886 PluginSettings *pset;
887 unsigned int setcount = m_PluginInfo.GetSettingsNum();
888 for (unsigned int i=0; i<setcount; i++)
890 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
894 pPlugin->m_type = pset->type_val;
897 for (unsigned int j=0; j<pset->opts_num; j++)
899 const char *key, *val;
900 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
905 if (!g_pVM->SetCompilationOption(co, key, val))
909 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
911 pPlugin->CancelMyCompile();
919 /* Do the actual compiling */
922 pPlugin->FinishMyCompile(error, maxlength);
927 if (pPlugin->GetStatus() == Plugin_Created)
929 AddCoreNativesToPlugin(pPlugin);
930 pPlugin->InitIdentity();
931 if (pPlugin->Call_AskPluginLoad(error, maxlength))
933 /* Autoload any modules */
934 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
938 /* Save the time stamp */
939 time_t t = pPlugin->GetFileTimeStamp();
940 pPlugin->SetTimeStamp(t);
947 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
950 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
956 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
962 if (res == LoadRes_AlreadyLoaded)
970 /* Run second pass if we need to */
971 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
973 if (!RunSecondPass(pl, error, maxlength))
983 void CPluginManager::LoadAutoPlugin(const char *plugin)
987 char error[255] = "Unknown error";
989 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
991 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
992 pl->SetErrorState(Plugin_Failed, "%s", error);
995 if (res == LoadRes_Successful)
1001 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1003 List<IPluginsListener *>::iterator iter;
1004 IPluginsListener *pListener;
1006 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1008 pListener = (*iter);
1009 pListener->OnPluginCreated(pPlugin);
1012 m_plugins.push_back(pPlugin);
1013 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1016 void CPluginManager::LoadAll_SecondPass()
1018 List<CPlugin *>::iterator iter;
1022 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1025 if (pPlugin->GetStatus() == Plugin_Loaded)
1028 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1030 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1031 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1036 m_AllPluginsLoaded = true;
1039 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1048 IPluginContext *pBase = pPlugin->GetBaseContext();
1049 uint32_t num = pBase->GetPubVarsNum();
1050 sp_pubvar_t *pubvar;
1052 char pathfile[PLATFORM_MAX_PATH];
1054 for (uint32_t i=0; i<num; i++)
1056 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1060 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1062 pl = (_pl *)pubvar->offs;
1063 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1067 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1071 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1072 if (strcmp(pathfile, file) == 0)
1076 if (pl->required == false)
1078 IPluginFunction *pFunc;
1080 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1081 if ((pFunc=pBase->GetFunctionByName(buffer)))
1084 pFunc->Execute(&res);
1085 if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
1089 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1095 /* Check that we aren't registering the same library twice */
1096 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1098 pPlugin->m_RequiredLibs.push_back(name);
1102 List<CPlugin *>::iterator iter;
1105 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1108 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1118 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1129 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1131 /* Find any extensions this plugin needs */
1140 IPluginContext *pBase = pPlugin->GetBaseContext();
1141 uint32_t num = pBase->GetPubVarsNum();
1142 sp_pubvar_t *pubvar;
1144 char path[PLATFORM_MAX_PATH];
1146 for (uint32_t i=0; i<num; i++)
1148 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1152 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1154 ext = (_ext *)pubvar->offs;
1155 if (!ext->required && !ext->autoload)
1159 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1163 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1169 /* Attempt to auto-load if necessary */
1172 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1173 g_Extensions.LoadAutoExtension(path);
1175 } else if (pass == 2) {
1176 /* Is this required? */
1179 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1180 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1182 pExt = g_Extensions.FindExtensionByName(name);
1184 /* :TODO: should we bind to unloaded extensions?
1185 * Currently the extension manager will ignore this.
1187 if (!pExt || !pExt->IsRunning(NULL, 0))
1191 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1195 g_Extensions.BindChildPlugin(pExt, pPlugin);
1205 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1207 /* Second pass for extension requirements */
1208 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1213 /* Bind all extra natives */
1214 g_Extensions.BindAllNativesToPlugin(pPlugin);
1215 AddFakeNativesToPlugin(pPlugin);
1217 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1222 /* Find any unbound natives
1223 * Right now, these are not allowed
1225 IPluginContext *pContext = pPlugin->GetBaseContext();
1226 uint32_t num = pContext->GetNativesNum();
1227 sp_native_t *native;
1228 for (unsigned int i=0; i<num; i++)
1230 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1234 if (native->status == SP_NATIVE_UNBOUND
1235 && native->name[0] != '@'
1236 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1240 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1246 /* Finish by telling all listeners */
1247 List<IPluginsListener *>::iterator iter;
1248 IPluginsListener *pListener;
1249 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1251 pListener = (*iter);
1252 pListener->OnPluginLoaded(pPlugin);
1255 /* Tell this plugin to finish initializing itself */
1256 pPlugin->Call_OnPluginStart();
1258 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1259 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_fakeNatives.size())
1261 List<CPlugin *>::iterator pl_iter;
1263 for (pl_iter = m_plugins.begin();
1264 pl_iter != m_plugins.end();
1267 pOther = (*pl_iter);
1268 if ((pOther->GetStatus() == Plugin_Error
1269 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1270 || pOther->m_FakeNativesMissing)
1272 TryRefreshDependencies(pOther);
1277 /* Go through our libraries and tell other plugins they're added */
1278 List<String>::iterator s_iter;
1279 for (s_iter = pPlugin->m_Libraries.begin();
1280 s_iter != pPlugin->m_Libraries.end();
1283 OnLibraryAction((*s_iter).c_str(), false);
1289 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1291 List<sp_nativeinfo_t *>::iterator iter;
1293 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
1295 sp_nativeinfo_t *natives = (*iter);
1296 IPluginContext *ctx = pPlugin->GetBaseContext();
1298 /* Attempt to bind every native! */
1299 while (natives[i].func != NULL)
1301 ctx->BindNative(&natives[i++]);
1306 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1308 assert(pPlugin->GetBaseContext() != NULL);
1310 AddFakeNativesToPlugin(pPlugin);
1312 List<String>::iterator lib_iter;
1313 List<String>::iterator req_iter;
1314 List<CPlugin *>::iterator pl_iter;
1316 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1319 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1322 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1324 if ((*req_iter) == (*lib_iter))
1332 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1337 /* Find any unbound natives
1338 * Right now, these are not allowed
1340 IPluginContext *pContext = pPlugin->GetBaseContext();
1341 uint32_t num = pContext->GetNativesNum();
1342 sp_native_t *native;
1343 for (unsigned int i=0; i<num; i++)
1345 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1349 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1351 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1356 if (pPlugin->GetStatus() == Plugin_Error)
1358 /* If we got here, all natives are okay again! */
1359 pPlugin->m_status = Plugin_Running;
1360 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1362 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1363 _SetPauseState(pPlugin, false);
1368 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1370 IPluginContext *pContext = pPlugin->GetBaseContext();
1371 sp_nativeinfo_t native;
1373 List<FakeNative *>::iterator iter;
1374 FakeNative *pNative;
1376 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1379 ctx = pNative->ctx->GetContext();
1380 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1382 /* Ignore natives in paused plugins */
1385 native.name = pNative->name.c_str();
1386 native.func = pNative->func;
1387 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1390 pContext->FindNativeByName(native.name, &idx);
1391 if (pPlugin->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL)
1393 WeakNative wkn(pPlugin, idx);
1394 GetPluginByCtx(ctx)->m_WeakNatives.push_back(wkn);
1397 /* Add us as a dependency, but we're careful not to do this circularly! */
1398 if (pNative->ctx != pContext)
1400 CPlugin *pOther = GetPluginByCtx(ctx);
1401 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1403 pOther->m_dependents.push_back(pPlugin);
1405 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1407 pPlugin->m_dependsOn.push_back(pOther);
1414 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1416 CPlugin *pPlugin = (CPlugin *)plugin;
1418 /* This prevents removal during insertion or anything else weird */
1419 if (m_plugins.find(pPlugin) == m_plugins.end())
1424 /* Remove us from the lookup table and linked list */
1425 m_plugins.remove(pPlugin);
1426 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1428 /* Go through our libraries and tell other plugins they're gone */
1429 List<String>::iterator s_iter;
1430 for (s_iter = pPlugin->m_Libraries.begin();
1431 s_iter != pPlugin->m_Libraries.end();
1434 OnLibraryAction((*s_iter).c_str(), true);
1437 /* Go through all dependent plugins and tell them this plugin is now gone */
1438 List<CPlugin *>::iterator pl_iter;
1440 for (pl_iter = pPlugin->m_dependents.begin();
1441 pl_iter != pPlugin->m_dependents.end();
1444 pOther = (*pl_iter);
1445 pOther->DependencyDropped(pPlugin);
1448 /* Tell everyone we depend on that we no longer exist */
1449 for (pl_iter = pPlugin->m_dependsOn.begin();
1450 pl_iter != pPlugin->m_dependsOn.end();
1453 pOther = (*pl_iter);
1454 pOther->m_dependents.remove(pPlugin);
1457 /* Remove weak references to us */
1458 for (pl_iter = m_plugins.begin();
1459 pl_iter != m_plugins.end();
1462 pOther = (*pl_iter);
1463 List<WeakNative>::iterator wk_iter = pOther->m_WeakNatives.begin();
1464 while (wk_iter != pOther->m_WeakNatives.end())
1466 if ((*wk_iter).pl == pPlugin)
1468 wk_iter = pOther->m_WeakNatives.erase(wk_iter);
1475 List<IPluginsListener *>::iterator iter;
1476 IPluginsListener *pListener;
1478 if (pPlugin->GetStatus() <= Plugin_Error)
1480 /* Notify listeners of unloading */
1481 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1483 pListener = (*iter);
1484 pListener->OnPluginUnloaded(pPlugin);
1487 pPlugin->Call_OnPluginEnd();
1490 /* Unbound weak natives */
1491 List<WeakNative>::iterator wk_iter;
1492 for (wk_iter=pPlugin->m_WeakNatives.begin(); wk_iter!=pPlugin->m_WeakNatives.end(); wk_iter++)
1494 WeakNative & wkn = (*wk_iter);
1495 sp_context_t *ctx = wkn.pl->GetContext();
1496 ctx->natives[wkn.idx].status = SP_NATIVE_UNBOUND;
1497 wkn.pl->m_FakeNativesMissing = true;
1500 /* Remove all of our native functions */
1501 List<FakeNative *>::iterator fn_iter;
1502 FakeNative *pNative;
1503 for (fn_iter = pPlugin->m_fakeNatives.begin();
1504 fn_iter != pPlugin->m_fakeNatives.end();
1507 pNative = (*fn_iter);
1508 m_Natives.remove(pNative);
1509 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1510 g_pVM->DestroyFakeNative(pNative->func);
1514 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1516 /* Notify listeners of destruction */
1517 pListener = (*iter);
1518 pListener->OnPluginDestroyed(pPlugin);
1521 /* Tell the plugin to delete itself */
1527 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1529 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1533 unsigned int CPluginManager::GetPluginCount()
1535 return m_plugins.size();
1538 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1540 m_listeners.push_back(listener);
1543 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1545 m_listeners.remove(listener);
1548 IPluginIterator *CPluginManager::GetPluginIterator()
1550 if (m_iters.empty())
1552 return new CPluginIterator(&m_plugins);
1554 CPluginIterator *iter = m_iters.front();
1561 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1566 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1568 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1569 size_t alias_len = 0;
1570 size_t local_len = 0;
1572 const char *ptr = alias;
1573 unsigned int alias_explicit_paths = 0;
1574 unsigned int alias_path_end = 0;
1575 while (*ptr != '\0')
1577 if (*ptr == '\\' || *ptr == '/')
1579 alias_explicit_paths++;
1580 alias_path_end = alias_len;
1586 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1588 /* Trailing slash is totally invalid here */
1593 unsigned int local_explicit_paths = 0;
1594 unsigned int local_path_end = 0;
1595 while (*ptr != '\0')
1597 if (*ptr == '\\' || *ptr == '/')
1599 local_explicit_paths++;
1600 local_path_end = local_len;
1606 /* If the alias has more explicit paths than the real path,
1607 * no match will be possible.
1609 if (alias_explicit_paths > local_explicit_paths)
1614 if (alias_explicit_paths)
1616 /* We need to find if the paths match now. For example, these should all match:
1618 * csdm optional/csdm
1619 * csdm/ban optional/crab/csdm/ban
1621 const char *aliasptr = alias;
1622 const char *localptr = localpath;
1626 if (*aliasptr != *localptr)
1628 /* We have to knock one path off */
1629 local_explicit_paths--;
1630 if (alias_explicit_paths > local_explicit_paths)
1632 /* Skip out if we're gonna have an impossible match */
1635 /* Eat up localptr tokens until we get a result */
1636 while (((localptr - localpath) < (int)local_path_end)
1638 && *localptr != '\\')
1642 /* Check if we hit the end of our searchable area.
1643 * This probably isn't possible because of the path
1644 * count check, but it's a good idea anyway.
1646 if ((localptr - localpath) >= (int)local_path_end)
1650 /* Consume the slash token */
1653 /* Reset the alias pointer so we can continue consuming */
1659 * This is safe because if localptr terminates early, aliasptr will too
1663 /* We should never reach the end of the string because of this check. */
1664 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1665 bool localend = (localptr - localpath) > (int)local_path_end;
1666 if (aliasend || localend)
1668 if (aliasend && localend)
1670 /* we matched, and we can break out now */
1674 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1679 /* If we got here, it's safe to compare the next two tokens */
1680 if (*localptr != *aliasptr)
1691 /* If we got here, it's time to compare filenames */
1692 const char *aliasptr = alias;
1693 const char *localptr = localpath;
1695 if (alias_explicit_paths)
1697 aliasptr = &alias[alias_path_end + 1];
1700 if (local_explicit_paths)
1702 localptr = &localpath[local_path_end + 1];
1707 if (*aliasptr == '*')
1709 /* First, see if this is the last character */
1710 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1712 /* If so, there's no need to match anything else */
1715 /* Otherwise, we need to search for an appropriate matching sequence in local.
1716 * Note that we only need to search up to the next asterisk.
1720 const char *local_orig = localptr;
1724 while (*aliasptr != '\0' && *aliasptr != '*')
1726 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1727 if (*aliasptr != *localptr)
1737 /* If we didn't get a match, we need to advance the search stream.
1738 * This will let us skip tokens while still searching for another match.
1740 localptr = ++local_orig;
1741 /* Make sure we don't go out of bounds */
1742 if (*localptr == '\0')
1753 /* If we got a match, move on to the next token */
1756 } else if (*aliasptr == '\0') {
1757 if (*localptr == '\0'
1759 strcmp(localptr, ".smx") == 0)
1765 } else if (*aliasptr != *localptr) {
1775 bool CPluginManager::IsLateLoadTime() const
1777 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1780 void CPluginManager::OnSourceModAllInitialized()
1782 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1785 g_HandleSys.InitAccessDefaults(NULL, &sec);
1787 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1788 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1790 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1791 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1793 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1795 g_ShareSys.AddInterface(NULL, this);
1798 void CPluginManager::OnSourceModShutdown()
1800 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1802 List<CPlugin *>::iterator iter;
1803 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1805 UnloadPlugin((*iter));
1808 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1809 g_ShareSys.DestroyIdentType(g_PluginIdent);
1810 g_ShareSys.DestroyIdentity(m_MyIdent);
1813 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1815 /* We don't care about the internal object, actually */
1818 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1820 m_natives.push_back(natives);
1823 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1831 sec.pIdentity = m_MyIdent;
1833 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1846 CPlugin *CPluginManager::GetPluginByOrder(int num)
1848 if (num < 1 || num > (int)GetPluginCount())
1856 IPluginIterator *iter = GetPluginIterator();
1857 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1859 pl = (CPlugin *)(iter->GetPlugin());
1865 const char *CPluginManager::GetStatusText(PluginStatus st)
1869 case Plugin_Running:
1875 case Plugin_Uncompiled:
1876 return "Uncompiled";
1877 case Plugin_BadLoad:
1887 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1891 const char *cmd = g_RootMenu.GetArgument(2);
1892 if (strcmp(cmd, "list") == 0)
1895 unsigned int id = 1;
1896 int plnum = GetPluginCount();
1900 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1903 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1906 IPluginIterator *iter = GetPluginIterator();
1907 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1909 IPlugin *pl = iter->GetPlugin();
1910 assert(pl->GetStatus() != Plugin_Created);
1912 const sm_plugininfo_t *info = pl->GetPublicInfo();
1913 if (pl->GetStatus() != Plugin_Running)
1915 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1917 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1919 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1920 if (IS_STR_FILLED(info->version))
1922 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1924 if (IS_STR_FILLED(info->author))
1926 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1928 g_RootMenu.ConsolePrint("%s", buffer);
1933 } else if (strcmp(cmd, "load") == 0) {
1936 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1942 const char *filename = g_RootMenu.GetArgument(3);
1944 char pluginfile[256];
1945 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
1946 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
1948 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1952 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
1958 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
1960 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
1964 } else if (strcmp(cmd, "unload") == 0) {
1967 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1972 int num = atoi(g_RootMenu.GetArgument(3));
1973 if (num < 1 || num > (int)GetPluginCount())
1975 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1979 IPluginIterator *iter = GetPluginIterator();
1980 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1982 IPlugin *pl = iter->GetPlugin();
1984 char name[PLATFORM_MAX_PATH];
1985 const sm_plugininfo_t *info = pl->GetPublicInfo();
1986 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1988 if (UnloadPlugin(pl))
1990 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1992 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1997 } else if (strcmp(cmd, "info") == 0) {
2000 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2004 int num = atoi(g_RootMenu.GetArgument(3));
2005 if (num < 1 || num > (int)GetPluginCount())
2007 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
2011 CPlugin *pl = GetPluginByOrder(num);
2012 const sm_plugininfo_t *info = pl->GetPublicInfo();
2014 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2015 if (pl->GetStatus() <= Plugin_Error)
2017 if (IS_STR_FILLED(info->name))
2019 if (IS_STR_FILLED(info->description))
2021 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2023 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2026 if (IS_STR_FILLED(info->author))
2028 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2030 if (IS_STR_FILLED(info->version))
2032 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2034 if (IS_STR_FILLED(info->url))
2036 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2038 if (pl->GetStatus() == Plugin_Error)
2040 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2042 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
2043 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
2045 const char *typestr = "";
2046 switch (pl->GetType())
2048 case PluginType_MapUpdated:
2049 typestr = "Map Change if Updated";
2051 case PluginType_MapOnly:
2052 typestr = "Map Change";
2054 case PluginType_Private:
2055 case PluginType_Global:
2060 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2063 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2064 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2065 info->name ? info->name : "<none>",
2066 info->version ? info->version : "<none>");
2067 if (IS_STR_FILLED(info->url))
2069 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2074 } else if (strcmp(cmd, "debug") == 0) {
2077 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
2081 int num = atoi(g_RootMenu.GetArgument(3));
2082 if (num < 1 || num > (int)GetPluginCount())
2084 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
2089 const char *mode = g_RootMenu.GetArgument(4);
2090 if ((res=strcmp("on", mode)) && strcmp("off", mode))
2092 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
2104 CPlugin *pl = GetPluginByOrder(num);
2105 if (debug && pl->IsDebugging())
2107 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
2109 } else if (!debug && !pl->IsDebugging()) {
2110 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
2115 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
2117 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
2120 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
2121 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
2127 /* Draw the main menu */
2128 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2129 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2130 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2131 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2132 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2133 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
2136 void CPluginManager::ReloadOrUnloadPlugins()
2138 List<CPlugin *>::iterator iter;
2139 List<CPlugin *> tmp_list = m_plugins;
2143 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2146 if (pl->GetType() == PluginType_MapOnly)
2148 UnloadPlugin((IPlugin *)pl);
2149 } else if (pl->GetType() == PluginType_MapUpdated) {
2150 t = pl->GetFileTimeStamp();
2151 if (!t || t > pl->GetTimeStamp())
2153 pl->SetTimeStamp(t);
2154 UnloadPlugin((IPlugin *)pl);
2160 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2162 List<IPluginsListener *>::iterator iter;
2163 IPluginsListener *pListener;
2164 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2166 pListener = (*iter);
2167 pListener->OnPluginPauseChange(pl, paused);
2171 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
2173 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
2178 FakeNative *pNative = new FakeNative;
2180 pNative->func = g_pVM->CreateFakeNative(func, pNative);
2187 pNative->call = pFunction;
2188 pNative->name.assign(name);
2189 pNative->ctx = pFunction->GetParentContext();
2191 m_Natives.push_back(pNative);
2192 sm_trie_insert(m_pNativeLookup, name,pNative);
2194 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
2195 pPlugin->m_fakeNatives.push_back(pNative);
2200 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2202 List<CPlugin *>::iterator iter;
2204 IPluginFunction *pFunction;
2206 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2210 if (pPlugin->GetStatus() <= Plugin_Paused)
2212 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2216 pForward->AddFunction(pFunction);
2222 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2224 if (pToken->type != g_PluginIdent)
2229 return (CPlugin *)(pToken->ptr);
2232 void CPluginManager::OnLibraryAction(const char *lib, bool drop)
2234 List<CPlugin *>::iterator iter;
2243 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2245 for (iter=m_plugins.begin();
2246 iter!=m_plugins.end();
2249 CPlugin *pl = (*iter);
2250 if (pl->GetStatus() != Plugin_Running)
2254 IPluginContext *pContext = pl->GetBaseContext();
2255 IPluginFunction *pf = pContext->GetFunctionByName(name);
2260 sp_context_t *ctx = pContext->GetContext();
2261 uint32_t num_vars = pContext->GetPubVarsNum();
2262 for (uint32_t i=0; i<num_vars; i++)
2264 sp_pubvar_t *pubvar;
2265 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2269 if (strncmp(pubvar->name, "__pl_", 5) != 0)
2273 plc = (_pl *)pubvar->offs;
2279 pContext->LocalToString(plc->name, &str);
2280 if (strcmp(str, lib) != 0)
2284 pf->PushString(lib);
2290 bool CPluginManager::LibraryExists(const char *lib)
2292 List<CPlugin *>::iterator iter;
2294 for (iter=m_plugins.begin();
2295 iter!=m_plugins.end();
2298 CPlugin *pl = (*iter);
2299 if (pl->GetStatus() != Plugin_Running)
2303 List<String>::iterator s_iter;
2304 for (s_iter = pl->m_Libraries.begin();
2305 s_iter != pl->m_Libraries.end();
2308 if ((*s_iter).compare(lib) == 0)