3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include "PluginSys.h"
35 #include "LibrarySys.h"
36 #include "HandleSys.h"
37 #include "ForwardSys.h"
38 #include "sourcemm_api.h"
39 #include "sourcemod.h"
40 #include "TextParsers.h"
42 #include "ExtensionSys.h"
43 #include "sm_srvcmds.h"
44 #include "sm_stringutil.h"
45 #include "ConCmdManager.h"
46 #include "PlayerManager.h"
47 #include "CoreConfig.h"
48 #include "Translator.h"
50 CPluginManager g_PluginSys;
51 HandleType_t g_PluginType = 0;
52 IdentityType_t g_PluginIdent = 0;
54 CPlugin::CPlugin(const char *file)
56 static int MySerial = 0;
58 m_type = PluginType_Private;
59 m_status = Plugin_Uncompiled;
60 m_serial = ++MySerial;
62 m_errormsg[256] = '\0';
63 snprintf(m_filename, sizeof(m_filename), "%s", file);
66 m_pProps = sm_trie_create();
67 m_FakeNativesMissing = false;
68 m_LibraryMissing = false;
69 m_bGotAllLoaded = false;
77 sec.pOwner = g_PluginSys.GetIdentity();
78 sec.pIdentity = sec.pOwner;
80 g_HandleSys.FreeHandle(m_handle, &sec);
81 g_ShareSys.DestroyIdentity(m_ident);
91 m_ctx.vm->FreeContext(m_ctx.ctx);
96 m_ctx.vm->AbortCompilation(m_ctx.co);
102 g_pSourcePawn->FreeFromMemory(m_plugin);
107 sm_trie_destroy(m_pProps);
109 for (size_t i=0; i<m_configs.size(); i++)
116 void CPlugin::InitIdentity()
120 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
121 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
122 m_ctx.base->SetIdentity(m_ident);
126 unsigned int CPlugin::CalcMemUsage()
128 unsigned int base_size =
130 + sizeof(IdentityToken_t)
131 + (m_PhraseFiles.size() * sizeof(unsigned int))
132 + (m_dependents.size() * sizeof(CPlugin *))
133 + (m_dependsOn.size() * sizeof(CPlugin *))
134 + (m_fakeNatives.size() * (sizeof(FakeNative *) + sizeof(FakeNative)))
135 + (m_WeakNatives.size() * sizeof(WeakNative))
136 + (m_configs.size() * (sizeof(AutoConfig *) + sizeof(AutoConfig)))
137 + sm_trie_mem_usage(m_pProps);
139 for (unsigned int i = 0; i < m_configs.size(); i++)
141 base_size += m_configs[i]->autocfg.size();
142 base_size += m_configs[i]->folder.size();
145 for (List<String>::iterator i = m_Libraries.begin();
146 i != m_Libraries.end();
149 base_size += (*i).size();
152 for (List<String>::iterator i = m_RequiredLibs.begin();
153 i != m_RequiredLibs.end();
156 base_size += (*i).size();
159 for (List<FakeNative *>::iterator i = m_fakeNatives.begin();
160 i != m_fakeNatives.end();
163 base_size += (*i)->name.size();
166 if (m_plugin != NULL)
168 base_size += sizeof(sp_plugin_t);
169 base_size += m_plugin->data_size;
170 base_size += m_plugin->pcode_size;
171 base_size += (m_plugin->info.natives_num * sizeof(sp_file_natives_t));
172 base_size += (m_plugin->info.publics_num * sizeof(sp_file_publics_t));
173 base_size += (m_plugin->info.pubvars_num * sizeof(sp_file_pubvars_t));
174 base_size += (m_plugin->debug.files_num * sizeof(sp_fdbg_file_t));
175 base_size += (m_plugin->debug.lines_num * sizeof(sp_fdbg_line_t));
176 base_size += (m_plugin->debug.syms_num * sizeof(sp_fdbg_symbol_t));
177 /* We can't get strtab size, oh well. */
180 if (m_ctx.base != NULL)
182 base_size += sizeof(BaseContext);
183 base_size += m_ctx.base->GetPublicsNum() * sizeof(CFunction);
185 if (m_ctx.ctx != NULL)
187 base_size += m_ctx.ctx->mem_size;
188 base_size += (m_plugin->debug.files_num * sizeof(sp_debug_file_t));
189 base_size += (m_plugin->debug.lines_num * sizeof(sp_debug_line_t));
190 base_size += (m_plugin->debug.syms_num * sizeof(sp_debug_symbol_t));
191 base_size += (m_plugin->info.pubvars_num * sizeof(sp_pubvar_t));
192 base_size += (m_plugin->info.publics_num * sizeof(sp_public_t));
193 base_size += (m_plugin->info.natives_num * sizeof(sp_native_t));
194 /* We also don't know the JIT code size, oh well. */
200 Handle_t CPlugin::GetMyHandle()
205 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
207 char fullpath[PLATFORM_MAX_PATH];
208 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
209 FILE *fp = fopen(fullpath, "rb");
211 CPlugin *pPlugin = new CPlugin(file);
217 snprintf(error, maxlength, "Unable to open file");
219 pPlugin->m_status = Plugin_BadLoad;
224 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
230 snprintf(error, maxlength, "Error %d while parsing plugin", err);
232 pPlugin->m_status = Plugin_BadLoad;
238 pPlugin->m_plugin = pl;
243 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
245 bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
247 if (exists && remove)
249 sm_trie_delete(m_pProps, prop);
255 bool CPlugin::SetProperty(const char *prop, void *ptr)
257 return sm_trie_insert(m_pProps, prop, ptr);
260 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
267 /* :NOTICE: We will eventually need to change these natives
268 * for swapping in new contexts
270 if (m_ctx.co || m_ctx.ctx)
275 m_status = Plugin_Uncompiled;
278 m_ctx.co = vm->StartCompilation(m_plugin);
283 void CPlugin::CancelMyCompile()
290 m_ctx.vm->AbortCompilation(m_ctx.co);
295 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
303 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
306 memset(&m_ctx, 0, sizeof(m_ctx));
309 snprintf(error, maxlength, "JIT failed to compile (error %d)", err);
314 m_ctx.base = new BaseContext(m_ctx.ctx);
315 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
317 m_status = Plugin_Created;
325 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
327 PluginStatus old_status = m_status;
330 if (old_status == Plugin_Running)
332 /* Tell everyone we're now paused */
333 g_PluginSys._SetPauseState(this, true);
337 va_start(ap, error_fmt);
338 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
343 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
347 void CPlugin::UpdateInfo()
349 /* Now grab the info */
351 IPluginContext *base = GetBaseContext();
352 int err = base->FindPubvarByName("myinfo", &idx);
354 memset(&m_info, 0, sizeof(m_info));
356 if (err == SP_ERROR_NONE)
358 struct sm_plugininfo_c_t
366 sm_plugininfo_c_t *cinfo;
369 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
370 base->LocalToString(cinfo->name, (char **)&m_info.name);
371 base->LocalToString(cinfo->description, (char **)&m_info.description);
372 base->LocalToString(cinfo->author, (char **)&m_info.author);
373 base->LocalToString(cinfo->url, (char **)&m_info.url);
374 base->LocalToString(cinfo->version, (char **)&m_info.version);
377 m_info.author = m_info.author ? m_info.author : "";
378 m_info.description = m_info.description ? m_info.description : "";
379 m_info.name = m_info.name ? m_info.name : "";
380 m_info.url = m_info.url ? m_info.url : "";
381 m_info.version = m_info.version ? m_info.version : "";
384 void CPlugin::Call_OnPluginStart()
386 if (m_status != Plugin_Loaded)
391 m_status = Plugin_Running;
394 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
401 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
403 SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
407 void CPlugin::Call_OnPluginEnd()
409 if (m_status > Plugin_Paused)
415 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
421 pFunction->Execute(&result);
424 void CPlugin::Call_OnAllPluginsLoaded()
426 if (m_status > Plugin_Paused)
436 m_bGotAllLoaded = true;
439 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnAllPluginsLoaded");
440 if (pFunction != NULL)
442 pFunction->Execute(&result);
447 if ((pFunction = m_ctx.base->GetFunctionByName("OnMapStart")) != NULL)
449 pFunction->Execute(NULL);
453 if (SM_AreConfigsExecuted())
455 SM_ExecuteForPlugin(GetBaseContext());
459 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
461 if (m_status != Plugin_Created)
466 m_status = Plugin_Loaded;
470 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
477 pFunction->PushCell(m_handle);
478 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
479 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
480 pFunction->PushCell(maxlength);
481 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
486 if (!result || m_status != Plugin_Loaded)
494 const sp_plugin_t *CPlugin::GetPluginStructure()
499 IPluginContext *CPlugin::GetBaseContext()
504 sp_context_t *CPlugin::GetContext()
509 const char *CPlugin::GetFilename()
514 PluginType CPlugin::GetType()
519 const sm_plugininfo_t *CPlugin::GetPublicInfo()
524 unsigned int CPlugin::GetSerial()
529 PluginStatus CPlugin::GetStatus()
534 bool CPlugin::IsDebugging()
541 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
544 void CPlugin::LibraryActions(bool dropping)
546 List<String>::iterator iter;
547 for (iter = m_Libraries.begin();
548 iter != m_Libraries.end();
551 g_PluginSys.OnLibraryAction((*iter).c_str(), true, dropping);
555 bool CPlugin::SetPauseState(bool paused)
557 if (paused && GetStatus() != Plugin_Running)
560 } else if (!paused && GetStatus() != Plugin_Paused) {
566 LibraryActions(true);
569 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
573 pFunction->PushCell(paused ? 1 : 0);
574 pFunction->Execute(&result);
579 m_status = Plugin_Paused;
580 m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
582 m_status = Plugin_Running;
583 m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
586 g_PluginSys._SetPauseState(this, paused);
590 LibraryActions(false);
596 IdentityToken_t *CPlugin::GetIdentity()
601 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
609 snprintf(error, maxlength, "Plugin is not runnable.");
614 if (debug && IsDebugging())
618 snprintf(error, maxlength, "Plugin is already in debug mode.");
622 else if (!debug && !IsDebugging())
626 snprintf(error, maxlength, "Plugins is already in production mode.");
631 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
632 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
636 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
641 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
645 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
646 new_ctx->hp = m_ctx.ctx->hp;
647 new_ctx->sp = m_ctx.ctx->sp;
648 new_ctx->frm = m_ctx.ctx->frm;
649 new_ctx->dbreak = m_ctx.ctx->dbreak;
650 new_ctx->context = m_ctx.ctx->context;
651 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
653 uint32_t nativeCount = m_plugin->info.natives_num;
654 for (uint32_t i=0; i<nativeCount; i++)
656 new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
657 new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
660 g_pVM->FreeContext(m_ctx.ctx);
662 m_ctx.base->SetContext(new_ctx);
670 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
678 bool CPlugin::IsRunnable()
680 return (m_status <= Plugin_Paused) ? true : false;
683 time_t CPlugin::GetFileTimeStamp()
685 char path[PLATFORM_MAX_PATH];
686 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
687 #ifdef PLATFORM_WINDOWS
689 if (_stat(path, &s) != 0)
690 #elif defined PLATFORM_POSIX
692 if (stat(path, &s) != 0)
703 time_t CPlugin::GetTimeStamp()
708 void CPlugin::SetTimeStamp(time_t t)
713 void CPlugin::AddLangFile(unsigned int index)
715 m_PhraseFiles.push_back(index);
718 size_t CPlugin::GetLangFileCount()
720 return m_PhraseFiles.size();
723 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
725 return m_PhraseFiles.at(index);
728 void CPlugin::DependencyDropped(CPlugin *pOwner)
735 List<String>::iterator reqlib_iter;
736 List<String>::iterator lib_iter;
737 for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
739 for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
741 if ((*reqlib_iter) == (*lib_iter))
743 m_LibraryMissing = true;
748 List<FakeNative *>::iterator iter;
752 unsigned int unbound = 0;
754 for (iter = pOwner->m_fakeNatives.begin();
755 iter != pOwner->m_fakeNatives.end();
759 /* Find this native! */
760 if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
765 m_ctx.base->GetNativeByIndex(idx, &native);
767 native->status = SP_NATIVE_UNBOUND;
773 m_FakeNativesMissing = true;
776 /* :IDEA: in the future, add native trapping? */
777 if (m_FakeNativesMissing || m_LibraryMissing)
779 SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
782 m_dependsOn.remove(pOwner);
785 unsigned int CPlugin::GetConfigCount()
787 return (unsigned int)m_configs.size();
790 AutoConfig *CPlugin::GetConfig(unsigned int i)
792 if (i >= GetConfigCount())
800 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
802 /* Do a check for duplicates to prevent double-execution */
803 for (size_t i = 0; i < m_configs.size(); i++)
805 if (m_configs[i]->autocfg.compare(cfg) == 0
806 && m_configs[i]->folder.compare(folder) == 0
807 && m_configs[i]->create == autoCreate)
813 AutoConfig *c = new AutoConfig;
817 c->create = autoCreate;
819 m_configs.push_back(c);
826 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
832 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
837 bool CPluginManager::CPluginIterator::MorePlugins()
839 return (current != mylist->end());
842 void CPluginManager::CPluginIterator::NextPlugin()
847 void CPluginManager::CPluginIterator::Release()
849 g_PluginSys.ReleaseIterator(this);
852 CPluginManager::CPluginIterator::~CPluginIterator()
856 void CPluginManager::CPluginIterator::Reset()
858 current = mylist->begin();
865 CPluginManager::CPluginManager()
867 m_LoadLookup = sm_trie_create();
868 m_AllPluginsLoaded = false;
870 m_pNativeLookup = sm_trie_create();
871 m_pCoreNatives = sm_trie_create();
872 m_LoadingLocked = false;
875 CPluginManager::~CPluginManager()
878 * Ignore the fact that there might be plugins in the cache.
879 * This usually means that Core is not being unloaded properly, and everything
880 * will crash anyway. YAY
882 sm_trie_destroy(m_LoadLookup);
883 sm_trie_destroy(m_pNativeLookup);
884 sm_trie_destroy(m_pCoreNatives);
886 CStack<CPluginManager::CPluginIterator *>::iterator iter;
887 for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
894 void CPluginManager::Shutdown()
896 List<CPlugin *>::iterator iter;
898 while ((iter = m_plugins.begin()) != m_plugins.end())
904 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
906 /* First read in the database of plugin settings */
909 m_AllPluginsLoaded = false;
910 if ((err=textparsers->ParseFile_SMC(config, &m_PluginInfo, &states)) != SMCError_Okay)
912 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
913 const char *err_msg = textparsers->GetSMCErrorString(err);
916 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
920 LoadPluginsFromDir(basedir, NULL);
923 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
925 char base_path[PLATFORM_MAX_PATH];
927 /* Form the current path to start reading from */
928 if (localpath == NULL)
930 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
932 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
935 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
940 g_LibSys.GetPlatformError(error, sizeof(error));
941 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
942 g_Logger.LogError("[SM] Platform returned error: %s", error);
946 while (dir->MoreFiles())
948 if (dir->IsEntryDirectory()
949 && (strcmp(dir->GetEntryName(), ".") != 0)
950 && (strcmp(dir->GetEntryName(), "..") != 0)
951 && (strcmp(dir->GetEntryName(), "disabled") != 0)
952 && (strcmp(dir->GetEntryName(), "optional") != 0))
954 char new_local[PLATFORM_MAX_PATH];
955 if (localpath == NULL)
957 /* If no path yet, don't add a former slash */
958 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
960 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
962 LoadPluginsFromDir(basedir, new_local);
963 } else if (dir->IsEntryFile()) {
964 const char *name = dir->GetEntryName();
965 size_t len = strlen(name);
967 && strcmp(&name[len-4], ".smx") == 0)
969 /* If the filename matches, load the plugin */
970 char plugin[PLATFORM_MAX_PATH];
971 if (localpath == NULL)
973 snprintf(plugin, sizeof(plugin), "%s", name);
975 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
977 LoadAutoPlugin(plugin);
982 g_LibSys.CloseDirectory(dir);
985 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
989 return LoadRes_NeverLoad;
992 bool no_load = false;
993 PluginSettings *pset;
994 unsigned int setcount = m_PluginInfo.GetSettingsNum();
995 for (unsigned int i=0; i<setcount; i++)
997 if ((pset = m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
1001 if (pset->blockload_val)
1009 * Does this plugin already exist?
1012 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
1014 /* Check to see if we should try reloading it */
1015 if (pPlugin->GetStatus() == Plugin_BadLoad
1016 || pPlugin->GetStatus() == Plugin_Error
1017 || pPlugin->GetStatus() == Plugin_Failed
1020 UnloadPlugin(pPlugin);
1028 return LoadRes_AlreadyLoaded;
1034 return LoadRes_NeverLoad;
1037 pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
1039 assert(pPlugin != NULL);
1041 pPlugin->m_type = PluginType_MapUpdated;
1043 ICompilation *co = NULL;
1045 if (pPlugin->m_status == Plugin_Uncompiled)
1047 co = pPlugin->StartMyCompile(g_pVM);
1050 for (unsigned int i=0; i<setcount; i++)
1052 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
1056 pPlugin->m_type = pset->type_val;
1059 for (unsigned int j=0; j<pset->opts_num; j++)
1061 const char *key, *val;
1062 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
1067 if (!g_pVM->SetCompilationOption(co, key, val))
1071 snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
1073 pPlugin->CancelMyCompile();
1081 /* Do the actual compiling */
1084 pPlugin->FinishMyCompile(error, maxlength);
1088 /* Get the status */
1089 if (pPlugin->GetStatus() == Plugin_Created)
1091 AddCoreNativesToPlugin(pPlugin);
1092 pPlugin->InitIdentity();
1093 if (pPlugin->Call_AskPluginLoad(error, maxlength))
1095 /* Autoload any modules */
1096 LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
1100 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1104 /* Save the time stamp */
1105 time_t t = pPlugin->GetFileTimeStamp();
1106 pPlugin->SetTimeStamp(t);
1113 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
1116 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
1122 if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
1128 if (res == LoadRes_AlreadyLoaded)
1134 if (res == LoadRes_NeverLoad)
1136 if (m_LoadingLocked)
1138 UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect");
1142 UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
1149 /* Run second pass if we need to */
1150 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
1152 if (!RunSecondPass(pl, error, maxlength))
1157 pl->Call_OnAllPluginsLoaded();
1163 void CPluginManager::LoadAutoPlugin(const char *plugin)
1167 char error[255] = "Unknown error";
1169 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
1171 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
1172 pl->SetErrorState(Plugin_Failed, "%s", error);
1175 if (res == LoadRes_Successful)
1181 void CPluginManager::AddPlugin(CPlugin *pPlugin)
1183 List<IPluginsListener *>::iterator iter;
1184 IPluginsListener *pListener;
1186 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1188 pListener = (*iter);
1189 pListener->OnPluginCreated(pPlugin);
1192 m_plugins.push_back(pPlugin);
1193 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
1196 void CPluginManager::LoadAll_SecondPass()
1198 List<CPlugin *>::iterator iter;
1202 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1205 if (pPlugin->GetStatus() == Plugin_Loaded)
1208 if (!RunSecondPass(pPlugin, error, sizeof(error)))
1210 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
1211 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
1216 m_AllPluginsLoaded = true;
1219 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
1228 IPluginContext *pBase = pPlugin->GetBaseContext();
1229 uint32_t num = pBase->GetPubVarsNum();
1230 sp_pubvar_t *pubvar;
1232 char pathfile[PLATFORM_MAX_PATH];
1234 for (uint32_t i=0; i<num; i++)
1236 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1240 if (strncmp(pubvar->name, "__pl_", 5) == 0)
1242 pl = (_pl *)pubvar->offs;
1243 if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
1247 if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
1251 g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
1252 if (strcmp(pathfile, file) == 0)
1256 if (pl->required == false)
1258 IPluginFunction *pFunc;
1260 UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
1261 if ((pFunc=pBase->GetFunctionByName(buffer)))
1264 pFunc->Execute(&res);
1265 if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
1269 snprintf(error, maxlength, "Fatal error during initializing plugin load");
1277 /* Check that we aren't registering the same library twice */
1278 if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
1280 pPlugin->m_RequiredLibs.push_back(name);
1286 List<CPlugin *>::iterator iter;
1289 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
1292 if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
1302 snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
1313 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
1315 /* Find any extensions this plugin needs */
1324 IPluginContext *pBase = pPlugin->GetBaseContext();
1325 uint32_t num = pBase->GetPubVarsNum();
1326 sp_pubvar_t *pubvar;
1328 char path[PLATFORM_MAX_PATH];
1330 for (uint32_t i=0; i<num; i++)
1332 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
1336 if (strncmp(pubvar->name, "__ext_", 6) == 0)
1338 ext = (_ext *)pubvar->offs;
1339 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
1343 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
1349 /* Attempt to auto-load if necessary */
1352 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1353 g_Extensions.LoadAutoExtension(path);
1358 /* Is this required? */
1361 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
1362 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
1364 pExt = g_Extensions.FindExtensionByName(name);
1366 /* :TODO: should we bind to unloaded extensions?
1367 * Currently the extension manager will ignore this.
1369 if (!pExt || !pExt->IsRunning(NULL, 0))
1373 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
1379 g_Extensions.BindChildPlugin(pExt, pPlugin);
1384 IPluginFunction *pFunc;
1386 UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
1388 if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
1391 pFunc->Execute(&res);
1392 if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
1396 UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
1409 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
1411 /* Second pass for extension requirements */
1412 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
1417 /* Bind all extra natives */
1418 g_Extensions.BindAllNativesToPlugin(pPlugin);
1420 if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
1425 AddFakeNativesToPlugin(pPlugin);
1427 /* Find any unbound natives
1428 * Right now, these are not allowed
1430 IPluginContext *pContext = pPlugin->GetBaseContext();
1431 uint32_t num = pContext->GetNativesNum();
1432 sp_native_t *native;
1433 for (unsigned int i=0; i<num; i++)
1435 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1439 if (native->status == SP_NATIVE_UNBOUND
1440 && native->name[0] != '@'
1441 && !(native->flags & SP_NTVFLAG_OPTIONAL))
1445 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
1451 /* Finish by telling all listeners */
1452 List<IPluginsListener *>::iterator iter;
1453 IPluginsListener *pListener;
1454 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1456 pListener = (*iter);
1457 pListener->OnPluginLoaded(pPlugin);
1460 /* Tell this plugin to finish initializing itself */
1461 pPlugin->Call_OnPluginStart();
1463 /* Now, if we have fake natives, go through all plugins that might need rebinding */
1464 if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_fakeNatives.size())
1466 List<CPlugin *>::iterator pl_iter;
1468 for (pl_iter = m_plugins.begin();
1469 pl_iter != m_plugins.end();
1472 pOther = (*pl_iter);
1473 if ((pOther->GetStatus() == Plugin_Error
1474 && (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
1475 || pOther->m_FakeNativesMissing)
1477 TryRefreshDependencies(pOther);
1482 /* Go through our libraries and tell other plugins they're added */
1483 List<String>::iterator s_iter;
1484 for (s_iter = pPlugin->m_Libraries.begin();
1485 s_iter != pPlugin->m_Libraries.end();
1488 OnLibraryAction((*s_iter).c_str(), true, false);
1491 /* Finally, add the core language file */
1492 pPlugin->AddLangFile(g_pCorePhraseID);
1497 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
1499 IPluginContext *pContext = pPlugin->GetBaseContext();
1502 uint32_t natives = pContext->GetNativesNum();
1503 sp_native_t *native;
1504 SPVM_NATIVE_FUNC pfn;
1505 for (uint32_t i=0; i<natives; i++)
1507 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1511 if (native->status == SP_NATIVE_BOUND)
1515 if (!sm_trie_retrieve(m_pCoreNatives, native->name, (void **)&pfn))
1519 pContext->BindNativeToIndex(i, pfn);
1523 SPVM_NATIVE_FUNC CPluginManager::FindCoreNative(const char *name)
1525 SPVM_NATIVE_FUNC pfn;
1527 if (!sm_trie_retrieve(m_pCoreNatives, name, (void **)&pfn))
1535 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
1537 assert(pPlugin->GetBaseContext() != NULL);
1539 AddFakeNativesToPlugin(pPlugin);
1541 List<String>::iterator lib_iter;
1542 List<String>::iterator req_iter;
1543 List<CPlugin *>::iterator pl_iter;
1545 for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
1548 for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
1551 for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
1553 if ((*req_iter) == (*lib_iter))
1561 pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
1566 /* Find any unbound natives
1567 * Right now, these are not allowed
1569 IPluginContext *pContext = pPlugin->GetBaseContext();
1570 uint32_t num = pContext->GetNativesNum();
1571 sp_native_t *native;
1572 for (unsigned int i=0; i<num; i++)
1574 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
1578 if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
1580 pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
1585 if (pPlugin->GetStatus() == Plugin_Error)
1587 /* If we got here, all natives are okay again! */
1588 pPlugin->m_status = Plugin_Running;
1589 if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1591 pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
1592 _SetPauseState(pPlugin, false);
1597 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
1599 IPluginContext *pContext = pPlugin->GetBaseContext();
1600 sp_nativeinfo_t native;
1602 List<FakeNative *>::iterator iter;
1603 FakeNative *pNative;
1605 for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
1608 ctx = pNative->ctx->GetContext();
1609 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
1611 /* Ignore natives in paused plugins */
1614 native.name = pNative->name.c_str();
1615 native.func = pNative->func;
1616 if (pContext->BindNative(&native) == SP_ERROR_NONE)
1619 pContext->FindNativeByName(native.name, &idx);
1620 if (pPlugin->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL)
1622 WeakNative wkn(pPlugin, idx);
1623 GetPluginByCtx(ctx)->m_WeakNatives.push_back(wkn);
1626 /* Add us as a dependency, but we're careful not to do this circularly! */
1627 if (pNative->ctx != pContext)
1629 CPlugin *pOther = GetPluginByCtx(ctx);
1630 if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
1632 pOther->m_dependents.push_back(pPlugin);
1634 if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
1636 pPlugin->m_dependsOn.push_back(pOther);
1643 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
1645 CPlugin *pPlugin = (CPlugin *)plugin;
1647 /* This prevents removal during insertion or anything else weird */
1648 if (m_plugins.find(pPlugin) == m_plugins.end())
1653 IPluginContext *pContext = plugin->GetBaseContext();
1654 if (pContext->IsInExec())
1657 UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
1658 engine->ServerCommand(buffer);
1662 /* Remove us from the lookup table and linked list */
1663 m_plugins.remove(pPlugin);
1664 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1666 /* Go through our libraries and tell other plugins they're gone */
1667 List<String>::iterator s_iter;
1668 for (s_iter = pPlugin->m_Libraries.begin();
1669 s_iter != pPlugin->m_Libraries.end();
1672 OnLibraryAction((*s_iter).c_str(), true, true);
1675 /* Go through all dependent plugins and tell them this plugin is now gone */
1676 List<CPlugin *>::iterator pl_iter;
1678 for (pl_iter = pPlugin->m_dependents.begin();
1679 pl_iter != pPlugin->m_dependents.end();
1682 pOther = (*pl_iter);
1683 pOther->DependencyDropped(pPlugin);
1686 /* Tell everyone we depend on that we no longer exist */
1687 for (pl_iter = pPlugin->m_dependsOn.begin();
1688 pl_iter != pPlugin->m_dependsOn.end();
1691 pOther = (*pl_iter);
1692 pOther->m_dependents.remove(pPlugin);
1695 /* Remove weak references to us */
1696 for (pl_iter = m_plugins.begin();
1697 pl_iter != m_plugins.end();
1700 pOther = (*pl_iter);
1701 List<WeakNative>::iterator wk_iter = pOther->m_WeakNatives.begin();
1702 while (wk_iter != pOther->m_WeakNatives.end())
1704 if ((*wk_iter).pl == pPlugin)
1706 wk_iter = pOther->m_WeakNatives.erase(wk_iter);
1713 List<IPluginsListener *>::iterator iter;
1714 IPluginsListener *pListener;
1716 if (pPlugin->GetStatus() <= Plugin_Error)
1718 /* Notify listeners of unloading */
1719 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1721 pListener = (*iter);
1722 pListener->OnPluginUnloaded(pPlugin);
1725 pPlugin->Call_OnPluginEnd();
1728 /* Unbound weak natives */
1729 List<WeakNative>::iterator wk_iter;
1730 for (wk_iter=pPlugin->m_WeakNatives.begin(); wk_iter!=pPlugin->m_WeakNatives.end(); wk_iter++)
1732 WeakNative & wkn = (*wk_iter);
1733 sp_context_t *ctx = wkn.pl->GetContext();
1734 ctx->natives[wkn.idx].status = SP_NATIVE_UNBOUND;
1735 wkn.pl->m_FakeNativesMissing = true;
1738 /* Remove all of our native functions */
1739 List<FakeNative *>::iterator fn_iter;
1740 FakeNative *pNative;
1741 for (fn_iter = pPlugin->m_fakeNatives.begin();
1742 fn_iter != pPlugin->m_fakeNatives.end();
1745 pNative = (*fn_iter);
1746 m_Natives.remove(pNative);
1747 sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
1748 g_pVM->DestroyFakeNative(pNative->func);
1752 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1754 /* Notify listeners of destruction */
1755 pListener = (*iter);
1756 pListener->OnPluginDestroyed(pPlugin);
1759 /* Tell the plugin to delete itself */
1765 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1767 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1771 unsigned int CPluginManager::GetPluginCount()
1773 return m_plugins.size();
1776 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1778 m_listeners.push_back(listener);
1781 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1783 m_listeners.remove(listener);
1786 IPluginIterator *CPluginManager::GetPluginIterator()
1788 if (m_iters.empty())
1790 return new CPluginIterator(&m_plugins);
1792 CPluginIterator *iter = m_iters.front();
1799 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1804 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1806 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1807 size_t alias_len = 0;
1808 size_t local_len = 0;
1810 const char *ptr = alias;
1811 unsigned int alias_explicit_paths = 0;
1812 unsigned int alias_path_end = 0;
1813 while (*ptr != '\0')
1815 if (*ptr == '\\' || *ptr == '/')
1817 alias_explicit_paths++;
1818 alias_path_end = alias_len;
1824 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1826 /* Trailing slash is totally invalid here */
1831 unsigned int local_explicit_paths = 0;
1832 unsigned int local_path_end = 0;
1833 while (*ptr != '\0')
1835 if (*ptr == '\\' || *ptr == '/')
1837 local_explicit_paths++;
1838 local_path_end = local_len;
1844 /* If the alias has more explicit paths than the real path,
1845 * no match will be possible.
1847 if (alias_explicit_paths > local_explicit_paths)
1852 if (alias_explicit_paths)
1854 /* We need to find if the paths match now. For example, these should all match:
1856 * csdm optional/csdm
1857 * csdm/ban optional/crab/csdm/ban
1859 const char *aliasptr = alias;
1860 const char *localptr = localpath;
1864 if (*aliasptr != *localptr)
1866 /* We have to knock one path off */
1867 local_explicit_paths--;
1868 if (alias_explicit_paths > local_explicit_paths)
1870 /* Skip out if we're gonna have an impossible match */
1873 /* Eat up localptr tokens until we get a result */
1874 while (((localptr - localpath) < (int)local_path_end)
1876 && *localptr != '\\')
1880 /* Check if we hit the end of our searchable area.
1881 * This probably isn't possible because of the path
1882 * count check, but it's a good idea anyway.
1884 if ((localptr - localpath) >= (int)local_path_end)
1888 /* Consume the slash token */
1891 /* Reset the alias pointer so we can continue consuming */
1897 * This is safe because if localptr terminates early, aliasptr will too
1901 /* We should never reach the end of the string because of this check. */
1902 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1903 bool localend = (localptr - localpath) > (int)local_path_end;
1904 if (aliasend || localend)
1906 if (aliasend && localend)
1908 /* we matched, and we can break out now */
1912 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1917 /* If we got here, it's safe to compare the next two tokens */
1918 if (*localptr != *aliasptr)
1929 /* If we got here, it's time to compare filenames */
1930 const char *aliasptr = alias;
1931 const char *localptr = localpath;
1933 if (alias_explicit_paths)
1935 aliasptr = &alias[alias_path_end + 1];
1938 if (local_explicit_paths)
1940 localptr = &localpath[local_path_end + 1];
1945 if (*aliasptr == '*')
1947 /* First, see if this is the last character */
1948 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1950 /* If so, there's no need to match anything else */
1953 /* Otherwise, we need to search for an appropriate matching sequence in local.
1954 * Note that we only need to search up to the next asterisk.
1958 const char *local_orig = localptr;
1962 while (*aliasptr != '\0' && *aliasptr != '*')
1964 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1965 if (*aliasptr != *localptr)
1975 /* If we didn't get a match, we need to advance the search stream.
1976 * This will let us skip tokens while still searching for another match.
1978 localptr = ++local_orig;
1979 /* Make sure we don't go out of bounds */
1980 if (*localptr == '\0')
1991 /* If we got a match, move on to the next token */
1994 } else if (*aliasptr == '\0') {
1995 if (*localptr == '\0'
1997 strcmp(localptr, ".smx") == 0)
2003 } else if (*aliasptr != *localptr) {
2013 bool CPluginManager::IsLateLoadTime() const
2015 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
2018 void CPluginManager::OnSourceModAllInitialized()
2020 m_MyIdent = g_ShareSys.CreateCoreIdentity();
2023 g_HandleSys.InitAccessDefaults(NULL, &sec);
2025 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
2026 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
2028 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
2029 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
2031 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
2033 g_ShareSys.AddInterface(NULL, this);
2036 void CPluginManager::OnSourceModShutdown()
2038 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
2042 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
2043 g_ShareSys.DestroyIdentType(g_PluginIdent);
2044 g_ShareSys.DestroyIdentity(m_MyIdent);
2047 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
2049 /* We don't care about the internal object, actually */
2052 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
2054 *pSize = ((CPlugin *)object)->CalcMemUsage();
2058 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
2060 for (unsigned int i = 0; natives[i].func != NULL; i++)
2062 sm_trie_insert(m_pCoreNatives, natives[i].name, (void *)natives[i].func);
2066 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
2074 sec.pIdentity = m_MyIdent;
2076 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
2089 CPlugin *CPluginManager::GetPluginByOrder(int num)
2091 if (num < 1 || num > (int)GetPluginCount())
2099 IPluginIterator *iter = GetPluginIterator();
2100 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
2102 pl = (CPlugin *)(iter->GetPlugin());
2108 const char *CPluginManager::GetStatusText(PluginStatus st)
2112 case Plugin_Running:
2118 case Plugin_Uncompiled:
2119 return "Uncompiled";
2120 case Plugin_BadLoad:
2130 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
2132 int argcount = command.ArgC();
2135 const char *cmd = command.Arg(2);
2136 if (strcmp(cmd, "list") == 0)
2139 unsigned int id = 1;
2140 int plnum = GetPluginCount();
2144 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
2149 g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
2152 IPluginIterator *iter = GetPluginIterator();
2153 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
2155 IPlugin *pl = iter->GetPlugin();
2156 assert(pl->GetStatus() != Plugin_Created);
2158 const sm_plugininfo_t *info = pl->GetPublicInfo();
2159 if (pl->GetStatus() != Plugin_Running)
2161 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
2165 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
2167 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2168 if (IS_STR_FILLED(info->version))
2170 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
2172 if (IS_STR_FILLED(info->author))
2174 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
2176 g_RootMenu.ConsolePrint("%s", buffer);
2182 else if (strcmp(cmd, "load") == 0)
2186 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
2192 const char *filename = command.Arg(3);
2194 char pluginfile[256];
2195 const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
2196 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
2198 IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
2202 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
2208 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
2212 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
2217 else if (strcmp(cmd, "unload") == 0)
2221 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
2227 const char *arg = command.Arg(3);
2228 int id = strtol(arg, &end, 10);
2232 pl = GetPluginByOrder(id);
2235 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2241 char pluginfile[256];
2242 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2243 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2245 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2247 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2252 char name[PLATFORM_MAX_PATH];
2253 const sm_plugininfo_t *info = pl->GetPublicInfo();
2254 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2256 if (UnloadPlugin(pl))
2258 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
2262 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
2267 else if (strcmp(cmd, "unload_all") == 0)
2269 g_PluginSys.UnloadAll();
2270 g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
2273 else if (strcmp(cmd, "load_lock") == 0)
2275 if (m_LoadingLocked)
2277 g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
2281 m_LoadingLocked = true;
2282 g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
2286 else if (strcmp(cmd, "load_unlock") == 0)
2288 if (m_LoadingLocked)
2290 m_LoadingLocked = false;
2291 g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
2295 g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
2299 else if (strcmp(cmd, "info") == 0)
2303 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
2309 const char *arg = command.Arg(3);
2310 int id = strtol(arg, &end, 10);
2314 pl = GetPluginByOrder(id);
2317 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2323 char pluginfile[256];
2324 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2325 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2327 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2329 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2334 const sm_plugininfo_t *info = pl->GetPublicInfo();
2336 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
2337 if (pl->GetStatus() <= Plugin_Error)
2339 if (IS_STR_FILLED(info->name))
2341 if (IS_STR_FILLED(info->description))
2343 g_RootMenu.ConsolePrint(" Title: %s (%s)", info->name, info->description);
2345 g_RootMenu.ConsolePrint(" Title: %s", info->name);
2348 if (IS_STR_FILLED(info->author))
2350 g_RootMenu.ConsolePrint(" Author: %s", info->author);
2352 if (IS_STR_FILLED(info->version))
2354 g_RootMenu.ConsolePrint(" Version: %s", info->version);
2356 if (IS_STR_FILLED(info->url))
2358 g_RootMenu.ConsolePrint(" URL: %s", info->url);
2360 if (pl->GetStatus() == Plugin_Error)
2362 g_RootMenu.ConsolePrint(" Error: %s", pl->m_errormsg);
2366 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
2367 g_RootMenu.ConsolePrint(" Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
2369 const char *typestr = "";
2370 switch (pl->GetType())
2372 case PluginType_MapUpdated:
2373 typestr = "Map Change if Updated";
2375 case PluginType_MapOnly:
2376 typestr = "Map Change";
2378 case PluginType_Private:
2379 case PluginType_Global:
2384 g_RootMenu.ConsolePrint(" Reloads: %s", typestr);
2389 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
2390 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
2391 info->name ? info->name : "<none>",
2392 info->version ? info->version : "<none>");
2393 if (IS_STR_FILLED(info->url))
2395 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
2401 else if (strcmp(cmd, "debug") == 0)
2405 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
2411 const char *arg = command.Arg(3);
2412 int id = strtol(arg, &end, 10);
2416 pl = GetPluginByOrder(id);
2419 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2425 char pluginfile[256];
2426 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2427 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2429 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2431 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2437 const char *mode = command.Arg(4);
2438 if ((res=strcmp("on", mode)) && strcmp("off", mode))
2440 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
2454 if (debug && pl->IsDebugging())
2456 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
2459 else if (!debug && !pl->IsDebugging())
2461 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
2466 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
2468 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
2473 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
2474 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
2478 else if (strcmp(cmd, "refresh") == 0)
2480 g_SourceMod.DoGlobalPluginLoads();
2481 g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
2484 else if (strcmp(cmd, "reload") == 0)
2488 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
2494 const char *arg = command.Arg(3);
2495 int id = strtol(arg, &end, 10);
2499 pl = GetPluginByOrder(id);
2502 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
2508 char pluginfile[256];
2509 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2510 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2512 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
2514 g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
2519 char name[PLATFORM_MAX_PATH];
2520 const sm_plugininfo_t *info = pl->GetPublicInfo();
2521 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
2523 if (ReloadPlugin(pl))
2525 g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
2529 g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
2536 /* Draw the main menu */
2537 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
2538 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
2539 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
2540 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
2541 g_RootMenu.DrawGenericOption("load", "Load a plugin");
2542 g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
2543 g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
2544 g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
2545 g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
2546 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
2547 g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
2550 bool CPluginManager::ReloadPlugin(CPlugin *pl)
2552 List<CPlugin *>::iterator iter;
2553 char filename[PLATFORM_MAX_PATH];
2554 bool debug, wasloaded;
2559 strcpy(filename, pl->m_filename);
2560 debug = pl->IsDebugging();
2561 ptype = pl->GetType();
2563 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
2571 if (!UnloadPlugin(pl))
2575 if (!(newpl=LoadPlugin(filename, debug, ptype, NULL, 0, &wasloaded)))
2580 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2582 if ((*iter) == (CPlugin *)newpl)
2584 m_plugins.erase(iter);
2590 for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
2593 m_plugins.insert(iter, (CPlugin *)newpl);
2598 void CPluginManager::ReloadOrUnloadPlugins()
2600 /* If we're in a load lock, just skip this whole bit. */
2601 if (m_LoadingLocked)
2606 List<CPlugin *>::iterator iter;
2607 List<CPlugin *> tmp_list = m_plugins;
2611 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
2614 if (pl->GetType() == PluginType_MapOnly)
2616 UnloadPlugin((IPlugin *)pl);
2618 else if (pl->GetType() == PluginType_MapUpdated)
2620 t = pl->GetFileTimeStamp();
2621 if (!t || t > pl->GetTimeStamp())
2623 pl->SetTimeStamp(t);
2624 UnloadPlugin((IPlugin *)pl);
2630 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
2632 List<IPluginsListener *>::iterator iter;
2633 IPluginsListener *pListener;
2634 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
2636 pListener = (*iter);
2637 pListener->OnPluginPauseChange(pl, paused);
2641 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
2643 if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
2648 FakeNative *pNative = new FakeNative;
2650 pNative->func = g_pVM->CreateFakeNative(func, pNative);
2657 pNative->call = pFunction;
2658 pNative->name.assign(name);
2659 pNative->ctx = pFunction->GetParentContext();
2661 m_Natives.push_back(pNative);
2662 sm_trie_insert(m_pNativeLookup, name,pNative);
2664 CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
2665 pPlugin->m_fakeNatives.push_back(pNative);
2670 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
2672 List<CPlugin *>::iterator iter;
2674 IPluginFunction *pFunction;
2676 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
2680 if (pPlugin->GetStatus() <= Plugin_Paused)
2682 pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
2686 pForward->AddFunction(pFunction);
2692 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
2694 if (pToken->type != g_PluginIdent)
2699 return (CPlugin *)(pToken->ptr);
2702 void CPluginManager::OnLibraryAction(const char *lib, bool is_a_plugin, bool drop)
2704 List<CPlugin *>::iterator iter;
2721 const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
2723 for (iter=m_plugins.begin();
2724 iter!=m_plugins.end();
2727 CPlugin *pl = (*iter);
2728 if (pl->GetStatus() != Plugin_Running)
2732 IPluginContext *pContext = pl->GetBaseContext();
2733 IPluginFunction *pf = pContext->GetFunctionByName(name);
2738 uint32_t num_vars = pContext->GetPubVarsNum();
2739 for (uint32_t i=0; i<num_vars; i++)
2741 sp_pubvar_t *pubvar;
2742 if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
2746 if (is_a_plugin && strncmp(pubvar->name, "__pl_", 5) == 0)
2748 plc = (_pl *)pubvar->offs;
2754 pContext->LocalToString(plc->name, &str);
2755 if (strcmp(str, lib) != 0)
2759 pf->PushString(lib);
2762 else if (!is_a_plugin && strncmp(pubvar->name, "__ext_", 6) == 0)
2764 ext = (_ext *)pubvar->offs;
2770 pContext->LocalToString(ext->name, &str);
2771 if (strcmp(str, lib) != 0)
2775 pf->PushString(lib);
2782 bool CPluginManager::LibraryExists(const char *lib)
2784 List<CPlugin *>::iterator iter;
2786 for (iter=m_plugins.begin();
2787 iter!=m_plugins.end();
2790 CPlugin *pl = (*iter);
2791 if (pl->GetStatus() != Plugin_Running)
2795 List<String>::iterator s_iter;
2796 for (s_iter = pl->m_Libraries.begin();
2797 s_iter != pl->m_Libraries.end();
2800 if ((*s_iter).compare(lib) == 0)
2810 void CPluginManager::AllPluginsLoaded()
2812 List<CPlugin *>::iterator iter;
2815 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
2818 pl->Call_OnAllPluginsLoaded();
2822 void CPluginManager::UnloadAll()
2824 List<CPlugin *>::iterator iter;
2825 while ( (iter = m_plugins.begin()) != m_plugins.end() )
2827 UnloadPlugin((*iter));
2831 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
2834 List<CPlugin *>::iterator iter;
2836 for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
2847 CPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
2853 id = strtol(arg, &end, 10);
2857 pl = GetPluginByOrder(id);
2865 char pluginfile[256];
2866 const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
2867 UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
2869 if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))