Optimized forwards, now paused functions are stored in a temp list so we dont have to check if they're runnable on each function execution.
2 * ===============================================================
3 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
4 * ===============================================================
6 * This file is not open source and may not be copied without explicit
7 * written permission of AlliedModders LLC. This file may not be redistributed
8 * in whole or significant part.
9 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
15 #include "PluginSys.h"
17 #include "LibrarySys.h"
18 #include "HandleSys.h"
19 #include "sourcemm_api.h"
20 #include "sourcemod.h"
21 #include "CTextParsers.h"
23 #include "ExtensionSys.h"
24 #include "sm_srvcmds.h"
25 #include "sm_stringutil.h"
27 CPluginManager g_PluginSys;
28 HandleType_t g_PluginType = 0;
29 IdentityType_t g_PluginIdent = 0;
31 CPlugin::CPlugin(const char *file)
33 static int MySerial = 0;
35 m_type = PluginType_Private;
36 m_status = Plugin_Uncompiled;
37 m_serial = ++MySerial;
39 m_errormsg[256] = '\0';
40 snprintf(m_filename, sizeof(m_filename), "%s", file);
50 sec.pOwner = g_PluginSys.GetIdentity();
51 sec.pIdentity = sec.pOwner;
53 g_HandleSys.FreeHandle(m_handle, &sec);
54 g_ShareSys.DestroyIdentity(m_ident);
64 m_ctx.vm->FreeContext(m_ctx.ctx);
69 m_ctx.vm->AbortCompilation(m_ctx.co);
75 g_pSourcePawn->FreeFromMemory(m_plugin);
80 void CPlugin::InitIdentity()
84 m_ident = g_ShareSys.CreateIdentity(g_PluginIdent);
85 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
86 m_ctx.base->SetIdentity(m_ident);
90 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
92 char fullpath[PLATFORM_MAX_PATH+1];
93 g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
94 FILE *fp = fopen(fullpath, "rb");
96 CPlugin *pPlugin = new CPlugin(file);
102 snprintf(error, maxlength, "Unable to open file");
104 pPlugin->m_status = Plugin_BadLoad;
109 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
115 snprintf(error, maxlength, "Error %d while parsing plugin", err);
117 pPlugin->m_status = Plugin_BadLoad;
123 pPlugin->m_plugin = pl;
128 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
135 /* :NOTICE: We will eventually need to change these natives
136 * for swapping in new contexts
138 if (m_ctx.co || m_ctx.ctx)
143 m_status = Plugin_Uncompiled;
146 m_ctx.co = vm->StartCompilation(m_plugin);
151 void CPlugin::CancelMyCompile()
158 m_ctx.vm->AbortCompilation(m_ctx.co);
163 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
171 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
174 memset(&m_ctx, 0, sizeof(m_ctx));
177 snprintf(error, maxlength, "Failed to compile (error %d)", err);
182 m_ctx.base = new BaseContext(m_ctx.ctx);
183 m_ctx.base->SetRunnable(false);
184 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
186 m_status = Plugin_Created;
194 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
199 va_start(ap, error_fmt);
200 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
205 m_ctx.base->SetRunnable(false);
209 void CPlugin::UpdateInfo()
211 /* Now grab the info */
213 IPluginContext *base = GetBaseContext();
214 int err = base->FindPubvarByName("myinfo", &idx);
216 memset(&m_info, 0, sizeof(m_info));
218 if (err == SP_ERROR_NONE)
220 struct sm_plugininfo_c_t
228 sm_plugininfo_c_t *cinfo;
231 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
232 base->LocalToString(cinfo->name, (char **)&m_info.name);
233 base->LocalToString(cinfo->description, (char **)&m_info.description);
234 base->LocalToString(cinfo->author, (char **)&m_info.author);
235 base->LocalToString(cinfo->url, (char **)&m_info.url);
236 base->LocalToString(cinfo->version, (char **)&m_info.version);
239 m_info.author = m_info.author ? m_info.author : "";
240 m_info.description = m_info.description ? m_info.description : "";
241 m_info.name = m_info.name ? m_info.name : "";
242 m_info.url = m_info.url ? m_info.url : "";
243 m_info.version = m_info.version ? m_info.version : "";
246 void CPlugin::Call_OnPluginStart()
248 if (m_status != Plugin_Loaded)
253 m_status = Plugin_Running;
256 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginStart");
262 pFunction->PushCell(m_handle);
263 pFunction->Execute(&result);
266 void CPlugin::Call_OnPluginEnd()
268 if (m_status < Plugin_Paused)
274 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginEnd");
280 pFunction->Execute(&result);
283 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
285 if (m_status != Plugin_Created)
290 m_status = Plugin_Loaded;
291 m_ctx.base->SetRunnable(true);
295 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("AskPluginLoad");
302 pFunction->PushCell(m_handle);
303 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
304 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
305 pFunction->PushCell(maxlength);
306 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
311 if (!result || m_status != Plugin_Loaded)
319 const sp_plugin_t *CPlugin::GetPluginStructure() const
324 IPluginContext *CPlugin::GetBaseContext() const
329 sp_context_t *CPlugin::GetContext() const
334 const char *CPlugin::GetFilename() const
339 PluginType CPlugin::GetType() const
344 const sm_plugininfo_t *CPlugin::GetPublicInfo() const
349 unsigned int CPlugin::GetSerial() const
354 PluginStatus CPlugin::GetStatus() const
359 bool CPlugin::IsDebugging() const
366 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
369 bool CPlugin::SetPauseState(bool paused)
371 if (paused && GetStatus() != Plugin_Paused)
374 } else if (!paused && GetStatus() != Plugin_Running) {
378 m_status = (paused) ? Plugin_Paused : Plugin_Running;
380 IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
384 pFunction->PushCell(paused ? 1 : 0);
385 pFunction->Execute(&result);
388 g_PluginSys._SetPauseState(this, paused);
393 IdentityToken_t *CPlugin::GetIdentity() const
398 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
406 snprintf(error, maxlength, "Plugin is not runnable.");
411 if (debug && IsDebugging())
415 snprintf(error, maxlength, "Plugin is already in debug mode.");
418 } else if (!debug && !IsDebugging()) {
421 snprintf(error, maxlength, "Plugins is already in production mode.");
426 ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
427 if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
431 snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
436 sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
440 memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
441 new_ctx->hp = m_ctx.ctx->hp;
442 new_ctx->sp = m_ctx.ctx->sp;
443 new_ctx->frm = m_ctx.ctx->frm;
444 new_ctx->dbreak = m_ctx.ctx->dbreak;
445 new_ctx->context = m_ctx.ctx->context;
446 memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
448 g_pVM->FreeContext(m_ctx.ctx);
450 m_ctx.base->SetContext(new_ctx);
456 snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
464 bool CPlugin::IsRunnable() const
466 return (m_status <= Plugin_Paused) ? true : false;
469 time_t CPlugin::GetFileTimeStamp()
471 char path[PLATFORM_MAX_PATH+1];
472 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
473 #ifdef PLATFORM_WINDOWS
475 if (_stat(path, &s) != 0)
476 #elif defined PLATFORM_POSIX
478 if (stat(path, &s) != 0)
481 g_Logger.LogError("Could not obtain plugin time stamp, error: %d", errno);
488 time_t CPlugin::GetTimeStamp() const
493 void CPlugin::SetTimeStamp(time_t t)
498 void CPlugin::AddLangFile(unsigned int index)
500 m_PhraseFiles.push_back(index);
503 size_t CPlugin::GetLangFileCount() const
505 return m_PhraseFiles.size();
508 unsigned int CPlugin::GetFileByIndex(unsigned int index) const
510 return m_PhraseFiles.at(index);
517 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
523 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
528 bool CPluginManager::CPluginIterator::MorePlugins()
530 return (current != mylist->end());
533 void CPluginManager::CPluginIterator::NextPlugin()
538 void CPluginManager::CPluginIterator::Release()
540 g_PluginSys.ReleaseIterator(this);
543 CPluginManager::CPluginIterator::~CPluginIterator()
547 void CPluginManager::CPluginIterator::Reset()
549 current = mylist->begin();
556 CPluginManager::CPluginManager()
558 m_LoadLookup = sm_trie_create();
559 m_AllPluginsLoaded = false;
563 CPluginManager::~CPluginManager()
566 * Ignore the fact that there might be plugins in the cache.
567 * This usually means that Core is not being unloaded properly, and everything
568 * will crash anyway. YAY
570 sm_trie_destroy(m_LoadLookup);
574 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
576 /* First read in the database of plugin settings */
578 unsigned int line, col;
579 m_AllPluginsLoaded = false;
580 if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
582 g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
583 const char *err_msg = g_TextParser.GetSMCErrorString(err);
586 g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
590 LoadPluginsFromDir(basedir, NULL);
593 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
595 char base_path[PLATFORM_MAX_PATH+1];
597 /* Form the current path to start reading from */
598 if (localpath == NULL)
600 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
602 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
605 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
610 g_LibSys.GetPlatformError(error, sizeof(error));
611 g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
612 g_Logger.LogError("[SM] Platform returned error: %s", error);
616 while (dir->MoreFiles())
618 if (dir->IsEntryDirectory()
619 && (strcmp(dir->GetEntryName(), ".") != 0)
620 && (strcmp(dir->GetEntryName(), "..") != 0)
621 && (strcmp(dir->GetEntryName(), "disabled") != 0)
622 && (strcmp(dir->GetEntryName(), "optional") != 0))
624 char new_local[PLATFORM_MAX_PATH+1];
625 if (localpath == NULL)
627 /* If no path yet, don't add a former slash */
628 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
630 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
632 LoadPluginsFromDir(basedir, new_local);
633 } else if (dir->IsEntryFile()) {
634 const char *name = dir->GetEntryName();
635 size_t len = strlen(name);
637 && strcmp(&name[len-4], ".smx") == 0)
639 /* If the filename matches, load the plugin */
640 char plugin[PLATFORM_MAX_PATH+1];
641 if (localpath == NULL)
643 snprintf(plugin, sizeof(plugin), "%s", name);
645 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
647 LoadAutoPlugin(plugin);
652 g_LibSys.CloseDirectory(dir);
655 //well i have discovered that gabe newell is very fat, so i wrote this comment now
656 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t err_max)
659 * Does this plugin already exist?
662 if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
664 /* Check to see if we should try reloading it */
665 if (pPlugin->GetStatus() == Plugin_BadLoad
666 || pPlugin->GetStatus() == Plugin_Error
667 || pPlugin->GetStatus() == Plugin_Failed)
669 UnloadPlugin(pPlugin);
675 return LoadRes_AlreadyLoaded;
679 pPlugin = CPlugin::CreatePlugin(path, error, err_max);
681 assert(pPlugin != NULL);
683 pPlugin->m_type = PluginType_MapUpdated;
685 ICompilation *co = NULL;
687 if (pPlugin->m_status == Plugin_Uncompiled)
689 co = pPlugin->StartMyCompile(g_pVM);
692 PluginSettings *pset;
693 unsigned int setcount = m_PluginInfo.GetSettingsNum();
694 for (unsigned int i=0; i<setcount; i++)
696 if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
700 pPlugin->m_type = pset->type_val;
703 for (unsigned int j=0; j<pset->opts_num; j++)
705 const char *key, *val;
706 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
711 if (!g_pVM->SetCompilationOption(co, key, val))
715 snprintf(error, err_max, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
717 pPlugin->CancelMyCompile();
725 /* Do the actual compiling */
728 pPlugin->FinishMyCompile(NULL, 0);
733 if (pPlugin->GetStatus() == Plugin_Created)
735 AddCoreNativesToPlugin(pPlugin);
736 pPlugin->InitIdentity();
737 if (pPlugin->Call_AskPluginLoad(error, err_max))
739 /* Autoload any modules */
740 LoadOrRequireExtensions(pPlugin, 1, error, err_max);
744 /* Save the time stamp */
745 time_t t = pPlugin->GetFileTimeStamp();
746 pPlugin->SetTimeStamp(t);
753 return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
756 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t err_max, bool *wasloaded)
762 if ((res=_LoadPlugin(&pl, path, debug, type, error, err_max)) == LoadRes_Failure)
768 if (res == LoadRes_AlreadyLoaded)
776 /* Run second pass if we need to */
777 if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
779 if (!RunSecondPass(pl, error, err_max))
789 void CPluginManager::LoadAutoPlugin(const char *plugin)
793 char error[255] = "Unknown error";
795 if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
797 g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
798 pl->SetErrorState(Plugin_Failed, "%s", error);
801 if (res == LoadRes_Successful)
807 void CPluginManager::AddPlugin(CPlugin *pPlugin)
809 List<IPluginsListener *>::iterator iter;
810 IPluginsListener *pListener;
812 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
815 pListener->OnPluginCreated(pPlugin);
818 m_plugins.push_back(pPlugin);
819 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
822 void CPluginManager::LoadAll_SecondPass()
824 List<CPlugin *>::iterator iter;
828 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
831 if (pPlugin->GetStatus() == Plugin_Loaded)
834 if (!RunSecondPass(pPlugin, error, sizeof(error)))
836 g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
837 pPlugin->SetErrorState(Plugin_Failed, "%s", error);
842 m_AllPluginsLoaded = true;
845 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
847 /* Find any extensions this plugin needs */
856 IPluginContext *pBase = pPlugin->GetBaseContext();
857 uint32_t num = pBase->GetPubVarsNum();
860 char path[PLATFORM_MAX_PATH+1];
862 for (uint32_t i=0; i<num; i++)
864 if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
868 if (strncmp(pubvar->name, "__ext_", 6) == 0)
870 ext = (_ext *)pubvar->offs;
871 if (!ext->required && !ext->autoload)
875 if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
879 if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
885 /* Attempt to auto-load if necessary */
888 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
889 g_Extensions.LoadAutoExtension(path);
891 } else if (pass == 2) {
892 /* Is this required? */
895 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
896 if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
898 pExt = g_Extensions.FindExtensionByName(name);
900 /* :TODO: should we bind to unloaded extensions?
901 * Currently the extension manager will ignore this.
903 if (!pExt || !pExt->IsRunning(NULL, 0))
907 snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
911 g_Extensions.BindChildPlugin(pExt, pPlugin);
921 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
923 /* Second pass for extension requirements */
924 if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
929 /* Bind all extra natives */
930 g_Extensions.BindAllNativesToPlugin(pPlugin);
932 /* Find any unbound natives
933 * Right now, these are not allowed
935 IPluginContext *pContext = pPlugin->GetBaseContext();
936 uint32_t num = pContext->GetNativesNum();
938 for (unsigned int i=0; i<num; i++)
940 if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
944 if (native->status == SP_NATIVE_UNBOUND)
948 snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
954 /* Finish by telling all listeners */
955 List<IPluginsListener *>::iterator iter;
956 IPluginsListener *pListener;
957 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
960 pListener->OnPluginLoaded(pPlugin);
963 /* Tell this plugin to finish initializing itself */
964 pPlugin->Call_OnPluginStart();
969 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
971 List<sp_nativeinfo_t *>::iterator iter;
973 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
975 sp_nativeinfo_t *natives = (*iter);
976 IPluginContext *ctx = pPlugin->GetBaseContext();
978 /* Attempt to bind every native! */
979 while (natives[i].func != NULL)
981 ctx->BindNative(&natives[i++]);
986 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
988 CPlugin *pPlugin = (CPlugin *)plugin;
990 /* This prevents removal during insertion or anything else weird */
991 if (m_plugins.find(pPlugin) == m_plugins.end())
996 List<IPluginsListener *>::iterator iter;
997 IPluginsListener *pListener;
999 if (pPlugin->GetStatus() <= Plugin_Error)
1001 /* Notify listeners of unloading */
1002 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1004 pListener = (*iter);
1005 pListener->OnPluginUnloaded(pPlugin);
1008 pPlugin->Call_OnPluginEnd();
1011 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1013 /* Notify listeners of destruction */
1014 pListener = (*iter);
1015 pListener->OnPluginDestroyed(pPlugin);
1018 /* Remove us from the lookup table and linked list */
1019 m_plugins.remove(pPlugin);
1020 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
1022 /* Tell the plugin to delete itself */
1028 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
1030 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
1034 unsigned int CPluginManager::GetPluginCount()
1036 return m_plugins.size();
1039 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
1041 m_listeners.push_back(listener);
1044 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
1046 m_listeners.remove(listener);
1049 IPluginIterator *CPluginManager::GetPluginIterator()
1051 if (m_iters.empty())
1053 return new CPluginIterator(&m_plugins);
1055 CPluginIterator *iter = m_iters.front();
1062 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
1067 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
1069 /* As an optimization, we do not call strlen, but compute the length in the first pass */
1070 size_t alias_len = 0;
1071 size_t local_len = 0;
1073 const char *ptr = alias;
1074 unsigned int alias_explicit_paths = 0;
1075 unsigned int alias_path_end = 0;
1076 while (*ptr != '\0')
1078 if (*ptr == '\\' || *ptr == '/')
1080 alias_explicit_paths++;
1081 alias_path_end = alias_len;
1087 if (alias_explicit_paths && alias_path_end == alias_len - 1)
1089 /* Trailing slash is totally invalid here */
1094 unsigned int local_explicit_paths = 0;
1095 unsigned int local_path_end = 0;
1096 while (*ptr != '\0')
1098 if (*ptr == '\\' || *ptr == '/')
1100 local_explicit_paths++;
1101 local_path_end = local_len;
1107 /* If the alias has more explicit paths than the real path,
1108 * no match will be possible.
1110 if (alias_explicit_paths > local_explicit_paths)
1115 if (alias_explicit_paths)
1117 /* We need to find if the paths match now. For example, these should all match:
1119 * csdm optional/csdm
1120 * csdm/ban optional/crab/csdm/ban
1122 const char *aliasptr = alias;
1123 const char *localptr = localpath;
1127 if (*aliasptr != *localptr)
1129 /* We have to knock one path off */
1130 local_explicit_paths--;
1131 if (alias_explicit_paths > local_explicit_paths)
1133 /* Skip out if we're gonna have an impossible match */
1136 /* Eat up localptr tokens until we get a result */
1137 while (((localptr - localpath) < (int)local_path_end)
1139 && *localptr != '\\')
1143 /* Check if we hit the end of our searchable area.
1144 * This probably isn't possible because of the path
1145 * count check, but it's a good idea anyway.
1147 if ((localptr - localpath) >= (int)local_path_end)
1151 /* Consume the slash token */
1154 /* Reset the alias pointer so we can continue consuming */
1160 * This is safe because if localptr terminates early, aliasptr will too
1164 /* We should never reach the end of the string because of this check. */
1165 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
1166 bool localend = (localptr - localpath) > (int)local_path_end;
1167 if (aliasend || localend)
1169 if (aliasend && localend)
1171 /* we matched, and we can break out now */
1175 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
1180 /* If we got here, it's safe to compare the next two tokens */
1181 if (*localptr != *aliasptr)
1192 /* If we got here, it's time to compare filenames */
1193 const char *aliasptr = alias;
1194 const char *localptr = localpath;
1196 if (alias_explicit_paths)
1198 aliasptr = &alias[alias_path_end + 1];
1201 if (local_explicit_paths)
1203 localptr = &localpath[local_path_end + 1];
1208 if (*aliasptr == '*')
1210 /* First, see if this is the last character */
1211 if ((unsigned)(aliasptr - alias) == alias_len - 1)
1213 /* If so, there's no need to match anything else */
1216 /* Otherwise, we need to search for an appropriate matching sequence in local.
1217 * Note that we only need to search up to the next asterisk.
1221 const char *local_orig = localptr;
1225 while (*aliasptr != '\0' && *aliasptr != '*')
1227 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1228 if (*aliasptr != *localptr)
1238 /* If we didn't get a match, we need to advance the search stream.
1239 * This will let us skip tokens while still searching for another match.
1241 localptr = ++local_orig;
1242 /* Make sure we don't go out of bounds */
1243 if (*localptr == '\0')
1254 /* If we got a match, move on to the next token */
1257 } else if (*aliasptr == '\0') {
1258 if (*localptr == '\0'
1260 strcmp(localptr, ".smx") == 0)
1266 } else if (*aliasptr != *localptr) {
1276 bool CPluginManager::IsLateLoadTime() const
1278 return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
1281 void CPluginManager::OnSourceModAllInitialized()
1283 m_MyIdent = g_ShareSys.CreateCoreIdentity();
1286 g_HandleSys.InitAccessDefaults(NULL, &sec);
1288 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
1289 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
1291 g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
1292 g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
1294 g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
1296 g_ShareSys.AddInterface(NULL, this);
1299 void CPluginManager::OnSourceModShutdown()
1301 g_RootMenu.RemoveRootConsoleCommand("plugins", this);
1303 List<CPlugin *>::iterator iter;
1304 while ( (iter = m_plugins.begin()) != m_plugins.end() )
1306 UnloadPlugin((*iter));
1309 g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
1310 g_ShareSys.DestroyIdentType(g_PluginIdent);
1311 g_ShareSys.DestroyIdentity(m_MyIdent);
1314 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1316 /* We don't care about the internal object, actually */
1319 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
1321 m_natives.push_back(natives);
1324 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
1332 sec.pIdentity = m_MyIdent;
1334 if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
1347 CPlugin *CPluginManager::GetPluginByOrder(int num)
1349 if (num < 1 || num > (int)GetPluginCount())
1357 IPluginIterator *iter = GetPluginIterator();
1358 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
1360 pl = (CPlugin *)(iter->GetPlugin());
1366 const char *CPluginManager::GetStatusText(PluginStatus st)
1370 case Plugin_Running:
1376 case Plugin_Uncompiled:
1377 return "Uncompiled";
1378 case Plugin_BadLoad:
1388 #define IS_STR_FILLED(var) (var[0] != '\0')
1389 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
1393 const char *cmd = g_RootMenu.GetArgument(2);
1394 if (strcmp(cmd, "list") == 0)
1397 unsigned int id = 1;
1398 int plnum = GetPluginCount();
1402 g_RootMenu.ConsolePrint("[SM] No plugins loaded");
1405 g_RootMenu.ConsolePrint("[SM] Displaying %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
1408 IPluginIterator *iter = GetPluginIterator();
1409 for (; iter->MorePlugins(); iter->NextPlugin(), id++)
1411 IPlugin *pl = iter->GetPlugin();
1412 assert(pl->GetStatus() != Plugin_Created);
1414 const sm_plugininfo_t *info = pl->GetPublicInfo();
1415 if (pl->GetStatus() != Plugin_Running)
1417 len += UTIL_Format(buffer, sizeof(buffer), " %02d <%s>", id, GetStatusText(pl->GetStatus()));
1419 len += UTIL_Format(buffer, sizeof(buffer), " %02d", id);
1421 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1422 if (IS_STR_FILLED(info->version))
1424 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
1426 if (IS_STR_FILLED(info->author))
1428 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1430 g_RootMenu.ConsolePrint("%s", buffer);
1435 } else if (strcmp(cmd, "load") == 0) {
1438 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
1444 const char *filename = g_RootMenu.GetArgument(3);
1445 IPlugin *pl = LoadPlugin(filename, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
1449 g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", filename);
1455 g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", filename);
1457 g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", filename, error);
1461 } else if (strcmp(cmd, "unload") == 0) {
1464 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
1469 int num = atoi(g_RootMenu.GetArgument(3));
1470 if (num < 1 || num > (int)GetPluginCount())
1472 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
1476 IPluginIterator *iter = GetPluginIterator();
1477 for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
1479 IPlugin *pl = iter->GetPlugin();
1481 char name[PLATFORM_MAX_PATH+1];
1482 const sm_plugininfo_t *info = pl->GetPublicInfo();
1483 strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
1485 if (UnloadPlugin(pl))
1487 g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
1489 g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
1494 } else if (strcmp(cmd, "info") == 0) {
1497 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
1501 int num = atoi(g_RootMenu.GetArgument(3));
1502 if (num < 1 || num > (int)GetPluginCount())
1504 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1508 CPlugin *pl = GetPluginByOrder(num);
1509 const sm_plugininfo_t *info = pl->GetPublicInfo();
1511 g_RootMenu.ConsolePrint(" Filename: %s", pl->GetFilename());
1512 if (pl->GetStatus() <= Plugin_Error)
1514 if (IS_STR_FILLED(info->name))
1516 g_RootMenu.ConsolePrint(" Title: %s", info->name);
1518 if (IS_STR_FILLED(info->version))
1520 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1522 if (IS_STR_FILLED(info->url))
1524 g_RootMenu.ConsolePrint(" URL: %s", info->url);
1526 if (IS_STR_FILLED(info->author))
1528 g_RootMenu.ConsolePrint(" Author: %s", info->author);
1530 if (IS_STR_FILLED(info->version))
1532 g_RootMenu.ConsolePrint(" Version: %s", info->version);
1534 if (IS_STR_FILLED(info->description))
1536 g_RootMenu.ConsolePrint(" Description: %s", info->description);
1538 g_RootMenu.ConsolePrint(" Debugging: %s", pl->IsDebugging() ? "yes" : "no");
1539 g_RootMenu.ConsolePrint(" Paused: %s", pl->GetStatus() == Plugin_Running ? "no" : "yes");
1541 g_RootMenu.ConsolePrint(" Load error: %s", pl->m_errormsg);
1542 g_RootMenu.ConsolePrint(" File info: (title \"%s\") (version \"%s\")",
1543 info->name ? info->name : "<none>",
1544 info->version ? info->version : "<none>");
1545 if (IS_STR_FILLED(info->url))
1547 g_RootMenu.ConsolePrint(" File URL: %s", info->url);
1552 } else if (strcmp(cmd, "debug") == 0) {
1555 g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
1559 int num = atoi(g_RootMenu.GetArgument(3));
1560 if (num < 1 || num > (int)GetPluginCount())
1562 g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
1567 const char *mode = g_RootMenu.GetArgument(4);
1568 if ((res=strcmp("on", mode)) && strcmp("off", mode))
1570 g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
1582 CPlugin *pl = GetPluginByOrder(num);
1583 if (debug && pl->IsDebugging())
1585 g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
1587 } else if (!debug && !pl->IsDebugging()) {
1588 g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
1593 if (pl->ToggleDebugMode(debug, error, sizeof(error)))
1595 g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
1598 g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
1599 g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
1605 /* Draw the main menu */
1606 g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
1607 g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
1608 g_RootMenu.DrawGenericOption("load", "Load a plugin");
1609 g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
1610 g_RootMenu.DrawGenericOption("info", "Information about a plugin");
1611 g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
1614 void CPluginManager::ReloadOrUnloadPlugins()
1616 List<CPlugin *>::iterator iter;
1617 List<CPlugin *> tmp_list = m_plugins;
1621 for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
1624 if (pl->GetType() == PluginType_MapOnly)
1626 UnloadPlugin((IPlugin *)pl);
1627 } else if (pl->GetType() == PluginType_MapUpdated) {
1628 t=pl->GetFileTimeStamp();
1633 if (t > pl->GetTimeStamp())
1635 pl->SetTimeStamp(t);
1636 UnloadPlugin((IPlugin *)pl);
1642 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
1644 List<IPluginsListener *>::iterator iter;
1645 IPluginsListener *pListener;
1646 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
1648 pListener = (*iter);
1649 pListener->OnPluginPauseChange(pl, paused);