2 * vim: set ts=4 sw=4 tw=99 noet :
3 * =============================================================================
5 * Copyright (C) 2004-2009 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>.
30 #include "ConVarManager.h"
31 #include "HalfLife2.h"
32 #include "PluginSys.h"
33 #include "ForwardSys.h"
34 #include "HandleSys.h"
35 #include "sm_srvcmds.h"
36 #include "sm_stringutil.h"
37 #include <sh_vector.h>
38 #include <sm_trie_tpl.h>
40 ConVarManager g_ConVarManager;
42 #if SOURCE_ENGINE >= SE_ORANGEBOX
43 SH_DECL_HOOK3_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *, float);
45 SH_DECL_HOOK2_void(ICvar, CallGlobalChangeCallback, SH_NOATTRIB, false, ConVar *, const char *);
48 #if SOURCE_ENGINE != SE_DARKMESSIAH
49 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
50 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
53 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
54 typedef List<const ConVar *> ConVarList;
55 KTrie<ConVarInfo *> convar_cache;
57 class ConVarReentrancyGuard
60 ConVarReentrancyGuard *up;
62 static ConVarReentrancyGuard *chain;
64 ConVarReentrancyGuard(ConVar *cvar)
65 : cvar(cvar), up(chain)
70 ~ConVarReentrancyGuard()
72 assert(chain == this);
76 static bool IsCvarInChain(ConVar *cvar)
78 ConVarReentrancyGuard *guard = chain;
81 if (guard->cvar == cvar)
89 ConVarReentrancyGuard *ConVarReentrancyGuard::chain = NULL;
91 ConVarManager::ConVarManager() : m_ConVarType(0), m_bIsDLLQueryHooked(false), m_bIsVSPQueryHooked(false)
95 ConVarManager::~ConVarManager()
99 void ConVarManager::OnSourceModStartup(bool late)
103 /* Set up access rights for the 'ConVar' handle type */
104 sec.access[HandleAccess_Read] = 0;
105 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
106 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
108 /* Create the 'ConVar' handle type */
109 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
112 void ConVarManager::OnSourceModAllInitialized()
115 * Episode 2 has this function by default, but the older versions do not.
117 #if SOURCE_ENGINE == SE_EPISODEONE
118 if (g_SMAPI->GetGameDLLVersion() >= 6)
120 SH_ADD_HOOK(IServerGameDLL, OnQueryCvarValueFinished, gamedll, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
121 m_bIsDLLQueryHooked = true;
125 #if SOURCE_ENGINE >= SE_ORANGEBOX
126 SH_ADD_HOOK(ICvar, CallGlobalChangeCallbacks, icvar, SH_STATIC(OnConVarChanged), false);
128 SH_ADD_HOOK(ICvar, CallGlobalChangeCallback, icvar, SH_STATIC(OnConVarChanged), false);
131 g_PluginSys.AddPluginsListener(this);
133 /* Add the 'convars' option to the 'sm' console command */
134 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
137 void ConVarManager::OnSourceModShutdown()
139 List<ConVarInfo *>::iterator iter = m_ConVars.begin();
140 HandleSecurity sec(NULL, g_pCoreIdent);
142 /* Iterate list of ConVarInfo structures, remove every one of them */
143 while (iter != m_ConVars.end())
145 ConVarInfo *pInfo = (*iter);
147 iter = m_ConVars.erase(iter);
149 g_HandleSys.FreeHandle(pInfo->handle, &sec);
150 if (pInfo->pChangeForward != NULL)
152 g_Forwards.ReleaseForward(pInfo->pChangeForward);
154 if (pInfo->sourceMod)
156 /* If we created it, we won't be tracking it, therefore it is
157 * safe to remove everything in one go.
159 META_UNREGCVAR(pInfo->pVar);
160 delete [] pInfo->pVar->GetName();
161 delete [] pInfo->pVar->GetHelpText();
162 delete [] pInfo->pVar->GetDefault();
167 /* If we didn't create it, we might be tracking it. Also,
168 * it could be unreadable.
170 UntrackConCommandBase(pInfo->pVar, this);
173 /* It's not safe to read the name here, so we simply delete the
174 * the info struct and clear the lookup cache at the end.
178 convar_cache.clear();
180 #if SOURCE_ENGINE != SE_DARKMESSIAH
182 if (m_bIsDLLQueryHooked)
184 SH_REMOVE_HOOK(IServerGameDLL, OnQueryCvarValueFinished, gamedll, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
185 m_bIsDLLQueryHooked = false;
187 else if (m_bIsVSPQueryHooked)
189 SH_REMOVE_HOOK(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
190 m_bIsVSPQueryHooked = false;
194 #if SOURCE_ENGINE >= SE_ORANGEBOX
195 SH_REMOVE_HOOK(ICvar, CallGlobalChangeCallbacks, icvar, SH_STATIC(OnConVarChanged), false);
197 SH_REMOVE_HOOK(ICvar, CallGlobalChangeCallback, icvar, SH_STATIC(OnConVarChanged), false);
200 /* Remove the 'convars' option from the 'sm' console command */
201 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
203 g_PluginSys.RemovePluginsListener(this);
205 /* Remove the 'ConVar' handle type */
206 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
210 * Orange Box will never use this.
212 void ConVarManager::OnSourceModVSPReceived()
215 * Don't bother if the DLL is already hooked.
217 if (m_bIsDLLQueryHooked)
222 /* For later MM:S versions, use the updated API, since it's cleaner. */
223 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
224 int engine = g_SMAPI->GetSourceEngineBuild();
225 if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
230 if (g_HL2.IsOriginalEngine() || vsp_version < 2)
236 #if SOURCE_ENGINE != SE_DARKMESSIAH
237 SH_ADD_HOOK(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
238 m_bIsVSPQueryHooked = true;
242 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
244 ConVarInfo **pLookup = convar_cache.retrieve(name);
256 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
258 /* Only check convars that have not been created by SourceMod's core */
260 if (!convar_cache_lookup(name, &pInfo))
265 HandleSecurity sec(NULL, g_pCoreIdent);
267 /* Remove it from our cache */
268 m_ConVars.remove(pInfo);
269 convar_cache.remove(name);
271 /* Now make sure no plugins are referring to this pointer */
272 IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator();
273 while (pl_iter->MorePlugins())
275 IPlugin *pl = pl_iter->GetPlugin();
277 ConVarList *pConVarList;
278 if (pl->GetProperty("ConVarList", (void **)&pConVarList, true)
279 && pConVarList != NULL)
281 pConVarList->remove(pInfo->pVar);
284 pl_iter->NextPlugin();
288 g_HandleSys.FreeHandle(pInfo->handle, &sec);
292 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
294 ConVarList *pConVarList;
295 List<ConVarQuery>::iterator iter;
297 /* If plugin has a convar list, free its memory */
298 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
303 /* Remove convar queries for this plugin that haven't returned results yet */
304 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
306 ConVarQuery &query = (*iter);
307 if (query.pCallback->GetParentRuntime() == plugin->GetRuntime())
309 m_ConVarQueries.erase(iter);
314 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
318 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
320 *pSize = sizeof(ConVar) + sizeof(ConVarInfo);
324 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
326 int argcount = command.ArgC();
329 bool wantReset = false;
331 /* Get plugin index that was passed */
332 const char *arg = command.Arg(2);
333 if (argcount >= 4 && strcmp(arg, "reset") == 0)
336 arg = command.Arg(3);
339 /* Get plugin object */
340 CPlugin *plugin = g_PluginSys.FindPluginByConsoleArg(arg);
344 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", arg);
348 /* Get plugin name */
349 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
350 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
352 ConVarList *pConVarList;
353 ConVarList::iterator iter;
355 /* If no convar list... */
356 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
358 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
364 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
365 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
368 /* Iterate convar list and display/reset each one */
369 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
371 /*const */ConVar *pConVar = const_cast<ConVar *>(*iter);
374 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
382 g_RootMenu.ConsolePrint("[SM] Reset %d convars for: %s", pConVarList->size(), plname);
388 /* Display usage of subcommand */
389 g_RootMenu.ConsolePrint("[SM] Usage: sm cvars [reset] <plugin #>");
392 Handle_t ConVarManager::CreateConVar(IPluginContext *pContext, const char *name, const char *defaultVal, const char *description, int flags, bool hasMin, float min, bool hasMax, float max)
394 ConVar *pConVar = NULL;
395 ConVarInfo *pInfo = NULL;
398 /* Find out if the convar exists already */
399 pConVar = icvar->FindVar(name);
401 /* If the convar already exists... */
404 /* Add convar to plugin's list */
405 AddConVarToPluginList(pContext, pConVar);
407 /* First find out if we already have a handle to it */
408 if (convar_cache_lookup(name, &pInfo))
410 return pInfo->handle;
414 /* Create and initialize ConVarInfo structure */
415 pInfo = new ConVarInfo();
416 pInfo->sourceMod = false;
417 pInfo->pChangeForward = NULL;
418 pInfo->pVar = pConVar;
420 /* If we don't, then create a new handle from the convar */
421 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
422 if (hndl == BAD_HANDLE)
428 pInfo->handle = hndl;
430 /* Insert struct into caches */
431 m_ConVars.push_back(pInfo);
432 convar_cache.insert(name, pInfo);
433 TrackConCommandBase(pConVar, this);
439 /* Prevent creating a convar that has the same name as a console command */
440 if (FindCommand(name))
445 /* Create and initialize ConVarInfo structure */
446 pInfo = new ConVarInfo();
447 pInfo->handle = hndl;
448 pInfo->sourceMod = true;
449 pInfo->pChangeForward = NULL;
451 /* Create a handle from the new convar */
452 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
453 if (hndl == BAD_HANDLE)
459 pInfo->handle = hndl;
461 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
462 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
463 pInfo->pVar = pConVar;
465 /* Add convar to plugin's list */
466 AddConVarToPluginList(pContext, pConVar);
468 /* Insert struct into caches */
469 m_ConVars.push_back(pInfo);
470 convar_cache.insert(name, pInfo);
475 Handle_t ConVarManager::FindConVar(const char *name)
477 ConVar *pConVar = NULL;
481 /* Search for convar */
482 pConVar = icvar->FindVar(name);
484 /* If it doesn't exist, then return an invalid handle */
490 /* At this point, the convar exists. So, find out if we already have a handle */
491 if (convar_cache_lookup(name, &pInfo))
493 return pInfo->handle;
496 /* Create and initialize ConVarInfo structure */
497 pInfo = new ConVarInfo();
498 pInfo->sourceMod = false;
499 pInfo->pChangeForward = NULL;
500 pInfo->pVar = pConVar;
502 /* If we don't have a handle, then create a new one */
503 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
504 if (hndl == BAD_HANDLE)
510 pInfo->handle = hndl;
512 /* Insert struct into our caches */
513 m_ConVars.push_back(pInfo);
514 convar_cache.insert(name, pInfo);
515 TrackConCommandBase(pConVar, this);
520 void ConVarManager::AddConVarChangeListener(const char *name, IConVarChangeListener *pListener)
524 if (FindConVar(name) == BAD_HANDLE)
529 /* Find the convar in the lookup trie */
530 if (convar_cache_lookup(name, &pInfo))
532 pInfo->changeListeners.push_back(pListener);
536 void ConVarManager::RemoveConVarChangeListener(const char *name, IConVarChangeListener *pListener)
540 /* Find the convar in the lookup trie */
541 if (convar_cache_lookup(name, &pInfo))
543 pInfo->changeListeners.remove(pListener);
547 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
550 IChangeableForward *pForward;
552 /* Find the convar in the lookup trie */
553 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
555 /* Get the forward */
556 pForward = pInfo->pChangeForward;
558 /* If forward does not exist, create it */
561 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
562 pInfo->pChangeForward = pForward;
565 /* Add function to forward's list */
566 pForward->AddFunction(pFunction);
570 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
573 IChangeableForward *pForward;
574 IPluginContext *pContext = pFunction->GetParentContext();
576 /* Find the convar in the lookup trie */
577 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
579 /* Get the forward */
580 pForward = pInfo->pChangeForward;
582 /* If the forward doesn't exist, we can't unhook anything */
585 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
589 /* Remove the function from the forward's list */
590 if (!pForward->RemoveFunction(pFunction))
592 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
596 /* If the forward now has 0 functions in it... */
597 if (pForward->GetFunctionCount() == 0 &&
598 !ConVarReentrancyGuard::IsCvarInChain(pConVar))
600 /* Free this forward */
601 g_Forwards.ReleaseForward(pForward);
602 pInfo->pChangeForward = NULL;
607 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
609 QueryCvarCookie_t cookie = 0;
611 #if SOURCE_ENGINE != SE_DARKMESSIAH
612 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
613 if (m_bIsDLLQueryHooked)
615 cookie = engine->StartQueryCvarValue(pPlayer, name);
617 #if SOURCE_ENGINE != SE_DOTA
618 else if (m_bIsVSPQueryHooked)
620 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
625 return InvalidQueryCvarCookie;
628 ConVarQuery query = {cookie, pCallback, hndl};
629 m_ConVarQueries.push_back(query);
635 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
637 ConVarList *pConVarList;
638 ConVarList::iterator iter;
639 bool inserted = false;
640 const char *orig = pConVar->GetName();
642 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
644 /* Check plugin for an existing convar list */
645 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
647 pConVarList = new ConVarList();
648 plugin->SetProperty("ConVarList", pConVarList);
650 else if (pConVarList->find(pConVar) != pConVarList->end())
652 /* If convar is already in list, then don't add it */
656 /* Insert convar into list which is sorted alphabetically */
657 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
659 if (strcmp(orig, (*iter)->GetName()) < 0)
661 pConVarList->insert(iter, pConVar);
669 pConVarList->push_back(pConVar);
673 #if SOURCE_ENGINE >= SE_ORANGEBOX
674 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue)
676 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
679 /* If the values are the same, exit early in order to not trigger callbacks */
680 if (strcmp(pConVar->GetString(), oldValue) == 0)
687 /* Find the convar in the lookup trie */
688 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
693 IChangeableForward *pForward = pInfo->pChangeForward;
695 if (pInfo->changeListeners.size() != 0)
697 for (List<IConVarChangeListener *>::iterator i = pInfo->changeListeners.begin();
698 i != pInfo->changeListeners.end();
701 #if SOURCE_ENGINE >= SE_ORANGEBOX
702 (*i)->OnConVarChanged(pConVar, oldValue, flOldValue);
704 (*i)->OnConVarChanged(pConVar, oldValue, atof(oldValue));
709 if (pForward != NULL)
711 ConVarReentrancyGuard guard(pConVar);
713 /* Now call forwards in plugins that have hooked this */
714 pForward->PushCell(pInfo->handle);
715 pForward->PushString(oldValue);
716 pForward->PushString(pConVar->GetString());
717 pForward->Execute(NULL);
721 bool ConVarManager::IsQueryingSupported()
723 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
726 #if SOURCE_ENGINE != SE_DARKMESSIAH
727 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
729 IPluginFunction *pCallback = NULL;
731 List<ConVarQuery>::iterator iter;
733 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
735 ConVarQuery &query = (*iter);
736 if (query.cookie == cookie)
738 pCallback = query.pCallback;
748 pCallback->PushCell(cookie);
749 pCallback->PushCell(IndexOfEdict(pPlayer));
750 pCallback->PushCell(result);
751 pCallback->PushString(cvarName);
753 if (result == eQueryCvarValueStatus_ValueIntact)
755 pCallback->PushString(cvarValue);
759 pCallback->PushString("\0");
762 pCallback->PushCell(value);
763 pCallback->Execute(&ret);
765 m_ConVarQueries.erase(iter);
770 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
775 if ((error = g_HandleSys.ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)