Triggering build against new mac libprotobuf.
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_DARKMESSIAH
43 #define CallGlobalChangeCallbacks CallGlobalChangeCallback
46 #if SOURCE_ENGINE >= SE_ORANGEBOX
47 SH_DECL_HOOK3_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *, float);
49 SH_DECL_HOOK2_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *);
52 #if SOURCE_ENGINE != SE_DARKMESSIAH
53 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
54 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
57 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
58 typedef List<const ConVar *> ConVarList;
59 KTrie<ConVarInfo *> convar_cache;
61 class ConVarReentrancyGuard
64 ConVarReentrancyGuard *up;
66 static ConVarReentrancyGuard *chain;
68 ConVarReentrancyGuard(ConVar *cvar)
69 : cvar(cvar), up(chain)
74 ~ConVarReentrancyGuard()
76 assert(chain == this);
80 static bool IsCvarInChain(ConVar *cvar)
82 ConVarReentrancyGuard *guard = chain;
85 if (guard->cvar == cvar)
93 ConVarReentrancyGuard *ConVarReentrancyGuard::chain = NULL;
95 ConVarManager::ConVarManager() : m_ConVarType(0), m_bIsDLLQueryHooked(false), m_bIsVSPQueryHooked(false)
99 ConVarManager::~ConVarManager()
103 void ConVarManager::OnSourceModStartup(bool late)
107 /* Set up access rights for the 'ConVar' handle type */
108 sec.access[HandleAccess_Read] = 0;
109 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
110 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
112 /* Create the 'ConVar' handle type */
113 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
116 void ConVarManager::OnSourceModAllInitialized()
119 * Episode 2 has this function by default, but the older versions do not.
121 #if SOURCE_ENGINE == SE_EPISODEONE
122 if (g_SMAPI->GetGameDLLVersion() >= 6)
124 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
125 m_bIsDLLQueryHooked = true;
129 SH_ADD_HOOK_STATICFUNC(ICvar, CallGlobalChangeCallbacks, icvar, 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_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
185 m_bIsDLLQueryHooked = false;
187 else if (m_bIsVSPQueryHooked)
189 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
190 m_bIsVSPQueryHooked = false;
194 SH_REMOVE_HOOK_STATICFUNC(ICvar, CallGlobalChangeCallbacks, icvar, OnConVarChanged, false);
196 /* Remove the 'convars' option from the 'sm' console command */
197 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
199 g_PluginSys.RemovePluginsListener(this);
201 /* Remove the 'ConVar' handle type */
202 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
206 * Orange Box will never use this.
208 void ConVarManager::OnSourceModVSPReceived()
211 * Don't bother if the DLL is already hooked.
213 if (m_bIsDLLQueryHooked)
218 /* For later MM:S versions, use the updated API, since it's cleaner. */
219 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
220 int engine = g_SMAPI->GetSourceEngineBuild();
221 if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
226 if (g_HL2.IsOriginalEngine() || vsp_version < 2)
232 #if SOURCE_ENGINE != SE_DARKMESSIAH
233 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
234 m_bIsVSPQueryHooked = true;
238 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
240 ConVarInfo **pLookup = convar_cache.retrieve(name);
252 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
254 /* Only check convars that have not been created by SourceMod's core */
256 if (!convar_cache_lookup(name, &pInfo))
261 HandleSecurity sec(NULL, g_pCoreIdent);
263 /* Remove it from our cache */
264 m_ConVars.remove(pInfo);
265 convar_cache.remove(name);
267 /* Now make sure no plugins are referring to this pointer */
268 IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator();
269 while (pl_iter->MorePlugins())
271 IPlugin *pl = pl_iter->GetPlugin();
273 ConVarList *pConVarList;
274 if (pl->GetProperty("ConVarList", (void **)&pConVarList, true)
275 && pConVarList != NULL)
277 pConVarList->remove(pInfo->pVar);
280 pl_iter->NextPlugin();
284 g_HandleSys.FreeHandle(pInfo->handle, &sec);
288 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
290 ConVarList *pConVarList;
291 List<ConVarQuery>::iterator iter;
293 /* If plugin has a convar list, free its memory */
294 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
299 /* Remove convar queries for this plugin that haven't returned results yet */
300 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
302 ConVarQuery &query = (*iter);
303 if (query.pCallback->GetParentRuntime() == plugin->GetRuntime())
305 m_ConVarQueries.erase(iter);
310 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
314 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
316 *pSize = sizeof(ConVar) + sizeof(ConVarInfo);
320 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
322 int argcount = command.ArgC();
325 bool wantReset = false;
327 /* Get plugin index that was passed */
328 const char *arg = command.Arg(2);
329 if (argcount >= 4 && strcmp(arg, "reset") == 0)
332 arg = command.Arg(3);
335 /* Get plugin object */
336 CPlugin *plugin = g_PluginSys.FindPluginByConsoleArg(arg);
340 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", arg);
344 /* Get plugin name */
345 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
346 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
348 ConVarList *pConVarList;
349 ConVarList::iterator iter;
351 /* If no convar list... */
352 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
354 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
360 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
361 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
364 /* Iterate convar list and display/reset each one */
365 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
367 /*const */ConVar *pConVar = const_cast<ConVar *>(*iter);
370 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
378 g_RootMenu.ConsolePrint("[SM] Reset %d convars for: %s", pConVarList->size(), plname);
384 /* Display usage of subcommand */
385 g_RootMenu.ConsolePrint("[SM] Usage: sm cvars [reset] <plugin #>");
388 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)
390 ConVar *pConVar = NULL;
391 ConVarInfo *pInfo = NULL;
394 /* Find out if the convar exists already */
395 pConVar = icvar->FindVar(name);
397 /* If the convar already exists... */
400 /* Add convar to plugin's list */
401 AddConVarToPluginList(pContext, pConVar);
403 /* First find out if we already have a handle to it */
404 if (convar_cache_lookup(name, &pInfo))
406 return pInfo->handle;
410 /* Create and initialize ConVarInfo structure */
411 pInfo = new ConVarInfo();
412 pInfo->sourceMod = false;
413 pInfo->pChangeForward = NULL;
414 pInfo->pVar = pConVar;
416 /* If we don't, then create a new handle from the convar */
417 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
418 if (hndl == BAD_HANDLE)
424 pInfo->handle = hndl;
426 /* Insert struct into caches */
427 m_ConVars.push_back(pInfo);
428 convar_cache.insert(name, pInfo);
429 TrackConCommandBase(pConVar, this);
435 /* Prevent creating a convar that has the same name as a console command */
436 if (FindCommand(name))
441 /* Create and initialize ConVarInfo structure */
442 pInfo = new ConVarInfo();
443 pInfo->handle = hndl;
444 pInfo->sourceMod = true;
445 pInfo->pChangeForward = NULL;
447 /* Create a handle from the new convar */
448 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
449 if (hndl == BAD_HANDLE)
455 pInfo->handle = hndl;
457 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
458 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
459 pInfo->pVar = pConVar;
461 /* Add convar to plugin's list */
462 AddConVarToPluginList(pContext, pConVar);
464 /* Insert struct into caches */
465 m_ConVars.push_back(pInfo);
466 convar_cache.insert(name, pInfo);
471 Handle_t ConVarManager::FindConVar(const char *name)
473 ConVar *pConVar = NULL;
477 /* Search for convar */
478 pConVar = icvar->FindVar(name);
480 /* If it doesn't exist, then return an invalid handle */
486 /* At this point, the convar exists. So, find out if we already have a handle */
487 if (convar_cache_lookup(name, &pInfo))
489 return pInfo->handle;
492 /* Create and initialize ConVarInfo structure */
493 pInfo = new ConVarInfo();
494 pInfo->sourceMod = false;
495 pInfo->pChangeForward = NULL;
496 pInfo->pVar = pConVar;
498 /* If we don't have a handle, then create a new one */
499 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
500 if (hndl == BAD_HANDLE)
506 pInfo->handle = hndl;
508 /* Insert struct into our caches */
509 m_ConVars.push_back(pInfo);
510 convar_cache.insert(name, pInfo);
511 TrackConCommandBase(pConVar, this);
516 void ConVarManager::AddConVarChangeListener(const char *name, IConVarChangeListener *pListener)
520 if (FindConVar(name) == BAD_HANDLE)
525 /* Find the convar in the lookup trie */
526 if (convar_cache_lookup(name, &pInfo))
528 pInfo->changeListeners.push_back(pListener);
532 void ConVarManager::RemoveConVarChangeListener(const char *name, IConVarChangeListener *pListener)
536 /* Find the convar in the lookup trie */
537 if (convar_cache_lookup(name, &pInfo))
539 pInfo->changeListeners.remove(pListener);
543 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
546 IChangeableForward *pForward;
548 /* Find the convar in the lookup trie */
549 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
551 /* Get the forward */
552 pForward = pInfo->pChangeForward;
554 /* If forward does not exist, create it */
557 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
558 pInfo->pChangeForward = pForward;
561 /* Add function to forward's list */
562 pForward->AddFunction(pFunction);
566 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
569 IChangeableForward *pForward;
570 IPluginContext *pContext = pFunction->GetParentContext();
572 /* Find the convar in the lookup trie */
573 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
575 /* Get the forward */
576 pForward = pInfo->pChangeForward;
578 /* If the forward doesn't exist, we can't unhook anything */
581 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
585 /* Remove the function from the forward's list */
586 if (!pForward->RemoveFunction(pFunction))
588 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
592 /* If the forward now has 0 functions in it... */
593 if (pForward->GetFunctionCount() == 0 &&
594 !ConVarReentrancyGuard::IsCvarInChain(pConVar))
596 /* Free this forward */
597 g_Forwards.ReleaseForward(pForward);
598 pInfo->pChangeForward = NULL;
603 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
605 QueryCvarCookie_t cookie = 0;
607 #if SOURCE_ENGINE != SE_DARKMESSIAH
608 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
609 if (m_bIsDLLQueryHooked)
611 cookie = engine->StartQueryCvarValue(pPlayer, name);
613 else if (m_bIsVSPQueryHooked)
615 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
619 return InvalidQueryCvarCookie;
622 ConVarQuery query = {cookie, pCallback, hndl};
623 m_ConVarQueries.push_back(query);
629 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
631 ConVarList *pConVarList;
632 ConVarList::iterator iter;
633 bool inserted = false;
634 const char *orig = pConVar->GetName();
636 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
638 /* Check plugin for an existing convar list */
639 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
641 pConVarList = new ConVarList();
642 plugin->SetProperty("ConVarList", pConVarList);
644 else if (pConVarList->find(pConVar) != pConVarList->end())
646 /* If convar is already in list, then don't add it */
650 /* Insert convar into list which is sorted alphabetically */
651 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
653 if (strcmp(orig, (*iter)->GetName()) < 0)
655 pConVarList->insert(iter, pConVar);
663 pConVarList->push_back(pConVar);
667 #if SOURCE_ENGINE >= SE_ORANGEBOX
668 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue)
670 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
673 /* If the values are the same, exit early in order to not trigger callbacks */
674 if (strcmp(pConVar->GetString(), oldValue) == 0)
681 /* Find the convar in the lookup trie */
682 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
687 IChangeableForward *pForward = pInfo->pChangeForward;
689 if (pInfo->changeListeners.size() != 0)
691 for (List<IConVarChangeListener *>::iterator i = pInfo->changeListeners.begin();
692 i != pInfo->changeListeners.end();
695 #if SOURCE_ENGINE >= SE_ORANGEBOX
696 (*i)->OnConVarChanged(pConVar, oldValue, flOldValue);
698 (*i)->OnConVarChanged(pConVar, oldValue, atof(oldValue));
703 if (pForward != NULL)
705 ConVarReentrancyGuard guard(pConVar);
707 /* Now call forwards in plugins that have hooked this */
708 pForward->PushCell(pInfo->handle);
709 pForward->PushString(oldValue);
710 pForward->PushString(pConVar->GetString());
711 pForward->Execute(NULL);
715 bool ConVarManager::IsQueryingSupported()
717 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
720 #if SOURCE_ENGINE != SE_DARKMESSIAH
721 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
723 IPluginFunction *pCallback = NULL;
725 List<ConVarQuery>::iterator iter;
727 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
729 ConVarQuery &query = (*iter);
730 if (query.cookie == cookie)
732 pCallback = query.pCallback;
742 pCallback->PushCell(cookie);
743 pCallback->PushCell(IndexOfEdict(pPlayer));
744 pCallback->PushCell(result);
745 pCallback->PushString(cvarName);
747 if (result == eQueryCvarValueStatus_ValueIntact)
749 pCallback->PushString(cvarValue);
753 pCallback->PushString("\0");
756 pCallback->PushCell(value);
757 pCallback->Execute(&ret);
759 m_ConVarQueries.erase(iter);
764 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
769 if ((error = g_HandleSys.ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)